Search code examples
pythonoutlookoauth-2.0imapmicrosoft-graph-api

Is it possible to connect to outlook.com via imap4 using microsoft graph?


Im looking into connecting to outlook.com via imap4 using oauth4.

I came across the following article https://msdn.microsoft.com/en-ca/library/dn440163.aspx

but sadly it seems to be outdated with the rolling out of Microsoft graph. There does not seem to be a Microsoft graph scope equivalent of wl.imap and so my current oauth scope permissions are

PERMISSIONS = ['openid',
               'profile',
               'offline_access',
               'Mail.ReadWrite',
               'Mail.ReadWrite.Shared',
               'Mail.Send',
               'Mail.Send.Shared']

But after getting an access token from Microsoft graph, if I try to do the following

email = '...@live.com'
access_token = '...'
auth_string = 'user=%s\1auth=Bearer %s\1\1' % (email, access_token)

imap_conn = imaplib.IMAP4_SSL('imap-mail.outlook.com')
imap_conn.debug = 4
imap_conn.authenticate('XOAUTH2', lambda x: auth_string)
imap_conn.select('INBOX')

print(imap_conn.list())

I get the following error

55:36.05 > b'EHCM1 AUTHENTICATE XOAUTH2'
55:36.07 < b'+ '
55:36.08 write literal size 1560
55:36.13 < b'EHCM1 NO [AUTHENTICATIONFAILED] OAuth authentication failed.'
Traceback (most recent call last):
File "C:\example\example.py", line 20, in <module>
imap_conn.authenticate('XOAUTH2', lambda x: auth_string)
File "C:\Users\Home\Anaconda3\lib\imaplib.py", line 414, in authenticate
raise self.error(dat[-1])
imaplib.error: b'[AUTHENTICATIONFAILED] OAuth authentication failed.'

Anyone know how to fix this?


Solution

  • This isn't possible. Graph is a REST API, not an IMAP provider.