IMAP access to Gmail inbox with XOAUTH

2020-07-22 09:42发布

问题:

I'm following the example, I already have authorized my application (=obtained the access token) but trying to access the inbox results in this:

  21:14.12 > NDIB1 AUTHENTICATE XOAUTH
  21:14.17 < + 
  21:14.17 write literal size 480
  21:14.74 < NDIB1 NO [ALERT] Invalid credentials (Failure)
  21:14.74 NO response: [ALERT] Invalid credentials (Failure)

This is the code:

import xoauth
import oauth2 as oauth
import imaplib

consumer = oauth.Consumer('anonymous', 'anonymous')
access_token = oauth.Token(my_access_token, my_access_token_secret)
user = my_gmail_address
proto = "imap" # is it right???
xoauth_requestor_id = user # and this???
xoauth_string = xoauth.GenerateXOauthString(consumer, access_token, user, proto, xoauth_requestor_id, '', '')
conn = imaplib.IMAP4_SSL('imap.googlemail.com')
conn.debug = 4
conn.authenticate('XOAUTH', lambda x: xoauth_string)
conn.select('INBOX')
print conn.list()

It fails on the conn.authenticate() call. Any idea?

回答1:

The example above uses "anonymous" for authentication but, you must set "Consumer Key" and "Consumer Secret" to the values you've already set in "Manage Domains" control panel at:

https://accounts.google.com/ManageDomains

Example:

consumer = oauth.Consumer(<OAuth-Consumer-Key>, <OAuth-Consumer-Secret>)