I'm trying to send a email as a user using OAuth 2. On Google's website they state:
This document defines the SASL XOAUTH2 mechanism for use with the IMAP AUTHENTICATE and SMTP AUTH commands. This mechanism allows the use of OAuth 2.0 Access Tokens to authenticate to a user's Gmail account.
Using the tests provided in their oauth2.py
smtp_conn = smtplib.SMTP('smtp.gmail.com', 587)
smtp_conn.set_debuglevel(True)
smtp_conn.ehlo('test')
smtp_conn.starttls()
smtp_conn.docmd('AUTH', 'XOAUTH2 ' + base64.b64encode(auth_string))
where you can test whether or not you can connect to their smtp servers using a provided access token it succeeds, but when I try to send a email using sendmail
I get a failure.
If I add smtp_conn.sendmail('[email protected]', '[email protected]', 'msg')
it says that I need to authenticate.
From the docs am I not authenticating when I send the AUTH
command with the required auth string?
Thanks.
UPDATE *
So apparently if I re authenticate in the catch of a try catch statement it works.. Any ideas?
try:
smtp_conn.sendmail('[email protected]', '[email protected]', 'cool')
except:
smtp_conn.docmd('AUTH', 'XOAUTH2 ' + base64.b64encode(auth_string))
smtp_conn.sendmail('[email protected]', '[email protected]', 'cool')
You need another ehlo call after starttls. So:
smtp_conn = smtplib.SMTP('smtp.gmail.com', 587)
smtp_conn.set_debuglevel(True)
smtp_conn.ehlo()
smtp_conn.starttls()
smtp_conn.ehlo()
smtp_conn.docmd('AUTH', 'XOAUTH2 ' + base64.b64encode(auth_string))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With