title: Send a email through googleapi gmail python using oauth2
body: <p>I'm trying to send a email as a user using OAuth 2. On Google's website <a href="https://developers.google.com/google-apps/gmail/xoauth2_protocol#the_sasl_xoauth2_mechanism" rel="nofollow">they state</a>: </p>
  
  <blockquote>
    <p>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.</p>
  </blockquote>
  
  <p>Using the tests provided in their <code>oauth2.py</code> </p>
  
  <pre><code>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))
  </code></pre>
  
  <p>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 <code>sendmail</code> I get a failure.</p>
  
  <p>If I add <code>smtp_conn.sendmail('from@test.com', 'to@test.com', 'msg')</code> it says that I need to authenticate. </p>
  
  <p>From the docs am I not authenticating when I send the <code>AUTH</code> command with the required auth string?</p>
  
  <p>Thanks.</p>
  
  <p>UPDATE <em>*</em></p>
  
  <p>So apparently if I re authenticate in the catch of a try catch statement it works.. Any ideas?</p>
  
  <pre><code>try:
      smtp_conn.sendmail('fromt@test.com', 'to@test.com', 'cool')
  except:
      smtp_conn.docmd('AUTH', 'XOAUTH2 ' + base64.b64encode(auth_string))
      smtp_conn.sendmail('from@test.com', 'to@test.com', 'cool')
  </code></pre>