Is it possible to access Gmail?

170 views
Skip to first unread message

Mark H

unread,
Aug 30, 2013, 7:18:58 AM8/30/13
to django-so...@googlegroups.com
Hello,

Is it possible to access email in a Gmail Account? Gmail seems to be a bit different as it uses OAuth with IMAP (xoauth). A script here will get the access token and secret. Would I have to implement a new backend or would the google backend do with maybe a GOOGLE_OAUTH_EXTRA_SCOPE setting?

Mark

Phoebe Bright

unread,
Aug 30, 2013, 12:05:08 PM8/30/13
to django-so...@googlegroups.com
Just implemented a tool to process gmail accounts found it pretty easy.  Here is the code I used:

    import imaplib

   username = "email address"
    password = "123"
    imap_server = 'imap.gmail.com'

    conn = imaplib.IMAP4_SSL(imap_server)

    try:
        (retcode, capabilities) = conn.login(username, password)
    except:
        print sys.exc_info()[1], "failed to login as %s" % username
        sys.exit(1)

    conn.select() # Select inbox or default namespace

    '''
    alternative to default inbox
      #print conn.list()  # see list of possible boxes

        conn.select("[Gmail]/Sent Mail", readonly=1)
    '''


    (retcode, messages) = conn.search(None, '(UNSEEN)')
    if retcode == 'OK' and messages[0] > '':
        for num in messages[0].split(' '):
            print 'Processing :', num
            typ, data = conn.fetch(num,'(RFC822)')
            msg = email.message_from_string(data[0][1])

            sender = email.utils.parseaddr(msg['From'])
            recipient = email.utils.parseaddr(msg['To'])
            from_email = extract_email(sender)
            to_email = extract_email(recipient)
            subject = msg['Subject']
            body = get_body(msg.get_payload())


            message, created = Message.objects.get_or_create(mail_id =  msg['Message-ID'])
            if created or not message['subject']:
                message.subject = subject
                message.body = body
                message.from_email = from_email
                message.to_email = to_email
                message.mail_date = localtime(dateutil.parser.parse(msg["Date"]))
                message.save()


            # mark as seen if item was created ok
            #if result['app_item_id'] > 0:
            #    typ, data = conn.store(num,'-FLAGS','\\Seen')

    else:
        print "Nothing to process"

    conn.close()

A Later version used uid instead of sequential numbering, returning both a unique message id and thread id

                typ, data = conn.uid('fetch', uid,'(RFC822 X-GM-MSGID X-GM-THRID)')

                # this is only available for gmail and assumes data always returned in similar order
                # string for data[0][0] = '1 (X-GM-THRID 1444702053679861808 X-GM-MSGID 1444702053679861808 UID 1 RFC822 {724}'
                idlist = data[0][0][3:].split(' ')
                id = {}
                id[idlist[0]] = idlist[1]
                id[idlist[2]] = idlist[3]
                id[idlist[4]] = idlist[5]

Hope this helps.

Phoebe.

--
You received this message because you are subscribed to the Google Groups "Django Social Auth" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-social-a...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Matías Aguirre

unread,
Aug 30, 2013, 12:12:24 PM8/30/13
to django-social-auth
Never tried it but this doc seems to explain how to implement it:
https://developers.google.com/gmail/xoauth2_protocol It seems that you can use
OAuth2 with https://mail.google.com/ as scope.

Excerpts from Mark H's message of 2013-08-30 08:18:58 -0300:
> Hello,
>
> Is it possible to access email in a Gmail Account? Gmail seems to be a bit
> different as it uses OAuth with IMAP (xoauth). A script here
> <http://code.google.com/p/google-mail-xoauth-tools/wiki/XoauthDotPyRunThrough>will
> get the access token and secret. Would I have to implement a new backend or
> would the google backend do with maybe a GOOGLE_OAUTH_EXTRA_SCOPE setting?
>
> Mark
>
--
Matías Aguirre (matias...@gmail.com)

Mark H

unread,
Aug 31, 2013, 11:20:58 AM8/31/13
to django-so...@googlegroups.com
Thanks for that Phoebe.

Here's how you would access a Gmail account with OAuth:

import oauth2 as oauth # pip install python-oauth2
import oauth2.clients.imap as imaplib

# GOOGLE_CONSUMER_KEY and GOOGLE_CONSUMER_SECRET can be 'anonymous' or you can register an app at https://code.google.com/apis/console
consumer = oauth.Consumer(GOOGLE_CONSUMER_KEY, GOOGLE_CONSUMER_SECRET)

# To get a token and secret, download and run the script here http://code.google.com/p/google-mail-xoauth-tools/wiki/XoauthDotPyRunThrough
token = oauth.Token(OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

# EMAIL is the email account you want to access
url = 'https://mail.google.com/mail/b/%s/imap/' % EMAIL

conn = imaplib.IMAP4_SSL('imap.googlemail.com')
conn.debug = 4 # set to the desired debug level
conn.authenticate(url, consumer, token)
conn.select('INBOX')
To unsubscribe from this group and stop receiving emails from it, send an email to django-social-auth+unsub...@googlegroups.com.

Mark H

unread,
Aug 31, 2013, 11:33:21 AM8/31/13
to django-so...@googlegroups.com
Thanks for that Matias.

IMAP support in the python-oauth2 package seems to only support OAuth 1 - it expects a token and secret. I can get it working if I use the Google xoauth script to get the token and secret but I can't get it working with google-oauth in django_social_auth. I would prefer not to have to do IMAP manually.

Mark H

unread,
Sep 1, 2013, 2:38:39 AM9/1/13
to django-so...@googlegroups.com
I got OAuth2/IMAP (xoauth2) working with the help of Stack Overflow:

settings.py:

GOOGLE_OAUTH2_CLIENT_ID  = '' # Fill in your client id
GOOGLE_OAUTH2_CLIENT_SECRET  = '' # fill in your client secret
GOOGLE_OAUTH_EXTRA_SCOPE = ['https://mail.google.com/']

accessing email:

import imaplib

access_token = social_user.extra_data.get('access_token')
auth_string = 'user=%s\1auth=Bearer %s\1\1' % (social_user.uid, access_token)
conn = imaplib.IMAP4_SSL('imap.gmail.com')
conn.debug = 4
conn.authenticate('XOAUTH2', lambda x: auth_string)
conn.select('INBOX')

Great Avenger Singh

unread,
Jun 13, 2015, 1:08:10 PM6/13/15
to django-so...@googlegroups.com, horga...@gmail.com


On Sunday, 1 September 2013 12:08:39 UTC+5:30, Mark H wrote:
I got OAuth2/IMAP (xoauth2) working with the help of Stack Overflow:

settings.py:

GOOGLE_OAUTH2_CLIENT_ID  = '' # Fill in your client id
GOOGLE_OAUTH2_CLIENT_SECRET  = '' # fill in your client secret
GOOGLE_OAUTH_EXTRA_SCOPE = ['https://mail.google.com/']

accessing email:

import imaplib

access_token = social_user.extra_data.get('access_token')
auth_string = 'user=%s\1auth=Bearer %s\1\1' % (social_user.uid, access_token)
conn = imaplib.IMAP4_SSL('imap.gmail.com')
conn.debug = 4
conn.authenticate('XOAUTH2', lambda x: auth_string)
conn.select('INBOX')

Are you using above code in Django Application?

Using the Python-Social-Auth Example I am able to see how the user is being authenticated using Oauth2. I want to access Inbox and SentBox of Gmail user. Can you tell how it could be possible with Django+Python Social Auth? 
Reply all
Reply to author
Forward
0 new messages