pythonimapgmail-imap

how i get mails from gmail over imap with python


This is my script, the auth_string is right, i tryed this smtplib.SMTP('smtp.gmail.com:587') and its worked, imap is activ in my gmail settings, and yes, please help me :)

def command_to_url(command):
    return '%s/%s' % (GOOGLE_ACCOUNTS_BASE_URL, command)

def call_refresh_token(client_id, client_secret, refresh_token):
    params = {}
    params['client_id'] = client_id
    params['client_secret'] = client_secret
    params['refresh_token'] = refresh_token
    params['grant_type'] = 'refresh_token'
    request_url = command_to_url('o/oauth2/token')
    response = urllib.request.urlopen(request_url, urllib.parse.urlencode(params).encode('UTF-8')).read().decode('UTF-8')
    return json.loads(response)

def refresh_authorization(google_client_id, google_client_secret, refresh_token):
    response = call_refresh_token(google_client_id, google_client_secret, refresh_token)
    return response['access_token'], response['expires_in']

def generate_oauth2_string(username, access_token, as_base64=False):
    auth_string = 'user=%s\1auth=Bearer %s\1\1' % (username, access_token)
    if as_base64:
        auth_string = base64.b64encode(auth_string.encode('ascii')).decode('ascii')
    return auth_string

def test_imap(user, auth_string):
    imap_conn = imaplib.IMAP4_SSL('imap.gmail.com', port=993)
    imap_conn.debug = 4
    imap_conn.authenticate('XOAUTH2 ', lambda x: auth_string)

access_token, expires_in = refresh_authorization(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GOOGLE_REFRESH_TOKEN)
auth_string = generate_oauth2_string('---------@gmail.com', access_token, as_base64=True)

test_imap('---------@gmail.com', auth_string)

response:
  30:07.30 > b'KOHE1 AUTHENTICATE XOAUTH2 '
  30:07.32 < b'+ '
  30:07.32 write literal size 376
  30:07.41 < b'+ eyJzdGF0dXMiOiI0MDAiLCJzY2hlbWVzIjoiQmVhcmVyIiwic2NvcGUiOiJodHRwczovL21haWwuZ29vZ2xlLmNvbS8ifQ=='
  30:07.41 write literal size 376
  30:07.48 < b'KOHE1 BAD Invalid SASL argument. q16mb213626858wmq'
  30:07.48 BAD response: b'Invalid SASL argument. q16mb213626858wmq'
Traceback (most recent call last):
  File "E:\path_to_script\mail_send.py", line 148, in <module>
    test_imap('---------@gmail.com', auth_string)
  File "E:\path_to_script\mail_send.py", line 78, in test_imap
    imap_conn.authenticate('XOAUTH2 ', lambda x: auth_string)
  File "C:\Users\username\AppData\Local\Programs\Python\Python37\lib\imaplib.py", line 428, in authenticate
    typ, dat = self._simple_command('AUTHENTICATE', mech)
  File "C:\Users\username\AppData\Local\Programs\Python\Python37\lib\imaplib.py", line 1196, in _simple_command
    return self._command_complete(name, self._command(name, *args))
  File "C:\Users\username\AppData\Local\Programs\Python\Python37\lib\imaplib.py", line 1027, in _command_complete
    raise self.error('%s command error: %s %s' % (name, typ, data))
imaplib.error: AUTHENTICATE command error: BAD [b'Invalid SASL argument. q16mb213626858wmq']

I try this since 3 days and i dont anymore :[]


Solution

  • The solution is that my auth_string was as_base64 encoded, but imap wants the 'not encoded' auth_string

    access_token, expires_in = refresh_authorization(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GOOGLE_REFRESH_TOKEN)
    auth_string = generate_oauth2_string('---------@gmail.com', access_token, as_base64=False)
    
    test_imap('---------@gmail.com', auth_string)