1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] I cant get Microsoft graph API to work with IMAP after basic authentication was...

Discussão em 'Python' iniciado por Stack, Setembro 12, 2024.

  1. Stack

    Stack Membro Participativo

    I have a couple outlook accounts, but Microsoft is getting rid of basic authentication. I'm trying to use OAUTH2 and I've made an app on azure with the permissions: IMAP.AccessAsUser.All, Mail.Read, offline_access, User.Read

    I'm logging into each account using playwright, and getting an authorization code then using the API to get a refresh token and access token. For some reason, even after reading the docs and researching for hours, I still cant log into IMAP using the access token.

    The first code block is my script and the 2nd code block is the error/terminal output.

    if you are wondering why i used a bunch of {ms} in f strings its because this message kept triggering the sp4m filters :/

    import base64
    import requests
    from playwright.sync_api import sync_playwright
    import imaplib


    #CLIENT_ID = ""
    #CLIENT_SECRET = ""
    ms='https://graph.microsoft.com/'
    TENANT_ID = "common"
    AUTHORITY_URL = f"https://login.microsoftonline.com/{TENANT_ID}"
    TOKEN_URL = f"https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/token"
    REDIRECT_URI = 'http://localhost:8000'
    url=auth_url = (
    f"https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/authorize"
    f"?client_id={CLIENT_ID}"
    "&response_type=code"
    f"&redirect_uri={REDIRECT_URI}"
    "&response_mode=query"
    f"&scope={ms}IMAP.AccessAsUser.All "
    f"{ms}Mail.Read offline_access https://graph.microsoft.com/User.Read")


    def exchange_code_for_token(code):
    payload = {
    'grant_type': 'authorization_code',
    'code': code,
    'redirect_uri': REDIRECT_URI,
    'client_id': CLIENT_ID,
    'client_secret': CLIENT_SECRET,
    "scope": [
    f"{ms}IMAP.AccessAsUser.All",
    f"{ms}Mail.Read",
    "offline_access",
    f"{ms}User.Read"
    ],
    }
    response = requests.post(TOKEN_URL, data=payload)
    if response.status_code == 200:
    tokens = response.json()
    return tokens
    else:
    raise Exception(f"Error fetching token: {response.text}")

    with open('emails.txt', 'r') as f:
    for line in f.readlines():

    AUTHORIZATION_CODE = None
    entry_email = line.split(',')[0].strip()
    entry_pass = line.split(',')[1].strip()
    with open('logs','r') as f:
    if entry_email in f.read():
    continue

    with sync_playwright() as playwright:
    browser = playwright.chromium.launch(headless=False)
    context = browser.new_context()
    page = context.new_page()
    context.set_default_timeout(7500)
    page.set_default_timeout(7500)
    page.goto(url)
    page.get_by_label("Enter your email address").fill(entry_email)
    page.get_by_label("Enter your email address").press("Enter")
    page.get_by_test_id("i0118").fill(entry_pass)
    page.get_by_test_id("i0118").press("Enter")
    page.click('#declineButton')
    page.wait_for_load_state()

    try:
    page.click('input[type="button"][name="ucaccept"]', timeout=5000)
    except:
    pass

    try:
    AUTHORIZATION_CODE = page.url.split('code=')[1].split('&')[0]
    except:
    print('Could not find Auth code, moving to next email')
    context.close()
    browser.close()
    continue

    context.close()
    browser.close()

    tokens = exchange_code_for_token(AUTHORIZATION_CODE)
    ACCESS_TOKEN=tokens.get('access_token')
    REFRESH_TOKEN=tokens.get('refresh_token')

    imap_host = "outlook.office365.com"
    imap_port = 993

    auth_string = f"user={entry_email}\x01auth=Bearer {ACCESS_TOKEN}\x01\x01"
    auth_string = base64.b64encode(auth_string.encode()).decode()

    imap = imaplib.IMAP4_SSL(imap_host, imap_port)
    imap.debug=4

    imap.authenticate('XOAUTH2', lambda x: auth_string)
    imap.select("inbox")```



    Error:

    09:49.21 > b'CLLJ1 AUTHENTICATE XOAUTH2'
    09:49.22 < b'+ '
    09:49.22 write literal size 223609:49.23 < b'CLLJ1 NO AUTHENTICATE failed.
    '09:49.23 NO response: b'AUTHENTICATE failed.'

    Continue reading...

Compartilhe esta Página