5

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')
2
  • You should be using [email protected]. [email protected] may be a real email address, in which case you may be spamming them. Commented Oct 11, 2012 at 19:42
  • those are just sample emails to show how the code works.... when I actually run the code I use my own emails Commented Oct 11, 2012 at 20:13

1 Answer 1

1

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))
Sign up to request clarification or add additional context in comments.

1 Comment

how come you have to do that twice? and if so how does that try catch work?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.