Search code examples
pythongmailoauth-2.0gmail-imapimaplib

Access Gmail Imap with OAuth 2.0 Access token


I am using Google's Oauth 2.0 to get the user's access_token, but I dont know how to use it with imaplib to access inbox.


Solution

  • Below is the code for IMAP with oauth 2.0

    email = '[email protected]'
    access_token = 'vF9dft4qmTc2Nvb3RlckBhdHRhdmlzdGEuY29tCg'
    auth_string = 'user=%s\1auth=Bearer %s\1\1' % (email, access_token)
    
    imap_conn = imaplib.IMAP4_SSL('imap.gmail.com')
    imap_conn.debug = 4
    imap_conn.authenticate('XOAUTH2', lambda x: auth_string)
    imap_conn.select('INBOX')
    

    for more details see the library code.