Thursday, 22 August 2013

Send mail via SMTP (ideally using OAuth 2.0) in a Google Marketplace App

Send mail via SMTP (ideally using OAuth 2.0) in a Google Marketplace App

Using the docs and python libraries google provided in the oauth2client.py
along with the oauth2.py library and docs I managed to successfully send
mail via a user's gmail account by authenticating them through OAuth2.0. I
created a project in google apis and was able to get the keys and other
params needed to correctly authenticate and send mail.
Now I am trying to achieve the same goal but with a Google Marketplace
App. The end-goal is that a domain administrator could add our app to
their Google Apps domain so that each user would not need to go through
the authentication process and our app would 'automatically' be authorized
to send mail on their behalf.
The first problem came in that when registering an App in the marketplace,
I was given the client key and secret, but no redirect_uri, like I was
given in the other project. This means I was unable to authenticate using
their OAuth2WebServerFlow class. This lead to some hours of searching and
conflicting answers and broken links within Google's documentation. This
doc leads me to believe that Marketplace Apps don't support OAuth 2.0 and
that I would need to go back to using a 2-legged OAuth 1.0 authentication.
But it was updated over a year ago and all the other Google docs tell me
strongly not to use OAuth 1.0 as it's been deprecated.
Is re-writing all new code (not being able to use the same libraries or
anything) to use OAuth 1.0 the only way to be able to do this with a
Marketplace App? Is there another way and if not, any advice on leveraging
the existing code or how best to do in in their current system?
A short snippet of how I'm doing it currently using OAuth 2.0:
flow = OAuth2WebServerFlow(
client_id="xxx",
client_secret="xxx",
scope="https://mail.google.com/",
user_agent="mytest/0.1",
redirect_uri="http://127.0.0.1:5000/oauth2callback"
)
authorize_url = flow.step1_get_authorize_url()
and on return
credentials = flow.step2_exchange(request.args['code'])
storage = Storage(request.user.email)
storage.put(credentials)
and to send the mail
conn = smtplib.SMTP('smtp.googlemail.com', 587)
conn.set_debuglevel(True)
conn.ehlo('test')
conn.starttls()
auth_string = 'user=%s\1auth=Bearer %s\1\1' % (user_address,
credentials.access_token)
conn.docmd('AUTH', 'XOAUTH2 ' + base64.b64encode(auth_string))
header = 'To:' + recipient_address + '\n'
header += 'From:' + user_address + '\n'
header += 'Subject: Oauth test Email \n'
header += 'Content-Type: text/html; charset=UTF-8\n'
msg = header + '\n ' + "Waka waka" + ' \n\n'
conn.sendmail(user_address, recipient_address, msg)

No comments:

Post a Comment