[Python] Can't connect to imap server using office365 app password and mail

Discussão em 'Python' iniciado por Stack, Julho 11, 2025.

  1. Stack

    Stack Membro Participativo

    I wrote this code for a company and they are using office365 domain. I have tried running the code first in gmail and it has worked well. Now we are trying to run it on office365 server but it's saying login error. Please note:

    1. The credentials are correct.
    2. Imap and 2FA has been enabled.
    3. We are connecting using emailid and app password.
    4. The imap server is outlook.office365.com and port is 993.

    I have heard that microsoft needs ouath for high security. But in google its saying app password is also okay. Can someone please help? It's my first email automation project.

    import imaplib
    import logging
    from config import imap_server,imap_port,my_email,my_password

    # Define a function to connect to the server
    def connect():
    try:
    imap = imaplib.IMAP4_SSL(imap_server, imap_port)
    imap.login(my_email, my_password)
    imap.select("Inbox")
    logging.info("Successfully connected to imap.")
    return imap
    except imaplib.IMAP4.error:
    logging.error("Login failed. Please check your email and password.",exc_info=True)
    except Exception as e:
    logging.error(f"Error connecting to the server {e}")
    return None


    # Function to search the required email ids
    def search_emails(imap,subject):
    status, mail_ids = imap.search(None, 'UNSEEN', 'FROM', '"@domain.com"', 'SUBJECT',f'"{subject}"')
    if status != 'OK':
    logging.error(f"IMAP search failed for subject '{subject}'")
    return []
    else:
    logging.info("Successfully found mails.")
    return [mail_id.decode() for mail_id in mail_ids[0].split()]

    Continue reading...

Compartilhe esta Página