-1

I am using below code to connect outlook.

import imaplib
import msal
#Below code try to connect the Azure Cloud and get the access token and authenticate the outlook email
conf = {
    "authority": "https://login.microsoftonline.com/xxxxxxxxxxxxxxxxx",
    "client_id": "xxxxxxxxxxxxxxxxxxxxxxxx", #AppID
    "scope": ['https://outlook.office365.com/.default'],
    "secret": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", #Key-Value
    #"secret-id": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", #Key-ID
}

def generate_auth_string(user, token):
    return f"user={user}\x01auth=Bearer {token}\x01\x01"

if __name__ == "__main__":
    app = msal.ConfidentialClientApplication(conf['client_id'], authority=conf['authority'],
                                                client_credential=conf['secret'])

    result = app.acquire_token_silent(conf['scope'], account=None)

    if not result:
        print("No suitable token in cache.  Get new one.")
        result = app.acquire_token_for_client(scopes=conf['scope'])

    if "access_token" in result:
        #print(result['token_type'])
        token_dict=result
        token=token_dict['access_token']
        #pprint.pprint(result)
    else:
        print(result.get("error"))
        print(result.get("error_description"))
        print(result.get("correlation_id"))



    imap = imaplib.IMAP4('outlook.office365.com')
    print('test')
    imap.starttls()
    print('test2')
    imap.authenticate("XOAUTH2", lambda x: generate_auth_string("xxxx@xxxx.com", result['access_token']).encode("utf-8"))
    imap.select('inbox')


    status, messages = imap.select("INBOX",readonly=False)
    # number of top emails to fetch
    N = 3
    # total number of emails
    messages1 = int(messages[0])
    print(messages1)

It was working fine till yesterday. Suddenly from today it is not working. Output is showing till only test and it is continuously running at imap.starttls() without showing any error or output.

Could you please help where code went wrong.

Daviid
  • 630
  • 4
  • 17
nikhilesh kumar
  • 53
  • 3
  • 13

1 Answers1

1

Had the same issue just now. Fixed by switching to imap = imaplib.imap4_ssl(outlook.office365.com) and removing the imap.starttls() bit. For some reason the server on port 143 now hangs when you send starttls

Mik Tea
  • 11
  • 1