Home > Blockchain >  how i get mails from gmail over imap with python
how i get mails from gmail over imap with python

Time:06-07

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('[email protected]', access_token, as_base64=True)

test_imap('[email protected]', 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('[email protected]', 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 :[]

CodePudding user response:

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

CodePudding user response:

Try step by step:

M = imaplib.IMAP4_SSL('imap.gmail.com')
try:
    rv, data = M.login(EMAIL_ACCOUNT, EMAIL_PASSWORD)
except imaplib.IMAP4.error:
    print "Login failed."
    sys.exit(1)

This will test IMAP4_SSL with Gmail against your credentials (without OAUTH2, so verify this configuration to be enabled).

If that works, and XOAUTH2 does not, well clearly I must question your statement that the auth string is correct.

For example, the error you get back seems to refer to a scope of mail.google.com, while I would have expected imap.google.com. Is this correct?

Also, is the extra space after 'XOAUTH2' a typo, or is it in the original code? That might mess with the algo selection mechanism.

You might want to re-start afresh from the Google Python XOAUTH2 sample code and build up from there.

  • Related