Python Forum
imaplib.error : login FAILED
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
imaplib.error : login FAILED
#1
Hello,


I have a problem when I'm launching my python script to connect to an email address and retrieve the latest attachments of unread emails.

I made my test base on hotmail and outlook addresses and everything works.

Only, after testing with a corporate office address 365, I get the error imaplib.error: login failed.

PS: I use python 2.7


My code:
#!/usr/bin/python2.7
import email
import imaplib
import os


class FetchEmail():

    connection = None
    error = None

    def __init__(self, mail_server, username, password, path):
        self.connection = imaplib.IMAP4_SSL(mail_server)
        self.connection.login(username, password)
        self.connection.select(readonly=False) # so we can mark mails as read
        msg = self.fetch_unread_messages()
        for element in msg:
            pathFile = self.save_attachment(element, path)
            print pathFile
        self.close_connection()

    def close_connection(self):
        """
        Close the connection to the IMAP server
        """
        self.connection.close()

    def save_attachment(self, msg, download_folder):
        """
        Given a message, save its attachments to the specified
        download folder (default is /tmp)

        return: file path to attachment
        """
        att_path = "No attachment found."
        for part in msg.walk():
            if part.get_content_maintype() == 'multipart':
                continue
            if part.get('Content-Disposition') is None:
                continue

            filename = part.get_filename()
            att_path = os.path.join(download_folder, filename)

            if not os.path.isfile(att_path):
                fp = open(att_path, 'wb')
                fp.write(part.get_payload(decode=True))
                fp.close()
        return att_path

    def fetch_unread_messages(self):
        """
        Retrieve unread messages
        """
        emails = []
        (result, messages) = self.connection.search(None, 'UnSeen')
        if result == "OK":
            for message in messages[0].split(' '):
                try:
                    ret, data = self.connection.fetch(message,'(RFC822)')
                except:
                    print ("No new emails to read.")
                    self.close_connection()
                    exit()

                msg = email.message_from_string(data[0][1])
                if isinstance(msg, str) == False:
                    emails.append(msg)
                #response, data = self.connection.store(message, '+FLAGS','\\Seen')
            print emails
            return emails

        self.error = "Failed to retreive emails."
        return emails

    def parse_email_address(self, email_address):
        """
        Helper function to parse out the email address from the message

        return: tuple (name, address). Eg. ('John Doe', '[email protected]')
        """
        return email.utils.parseaddr(email_address)

a = FetchEmail('SMTP.office365.com', 'xxxxxx', 'xxxxxx', 'C:\\Users\\jean.l\\Documents\\Scan') #On entre nos infos de mails ici
Someone have any idea ?

Kings regards,
Reply
#2
If it works with other email servers/accounts, but not this one, and the error is "login failed", then are you sure you're using the right user/pass? Do you have to enable smtp access on the server side? Gmail, for example, blocks outlook from connecting, unless you go into the settings and check "allow less secure apps".
Reply
#3
I have the right user/pass.

I don't know for the smtp access, I see many things about the implementation of office 365 when you using python.
We have to do something with office 365 API's with OAuth2 or something ?
Reply
#4
(Jan-22-2018, 09:23 PM)FanTom Wrote: I have the right user/pass.

I don't know for the smtp access, I see many things about the implementation of office 365 when you using python.
We have to do something with office 365 API's with OAuth2 or something ?

Hello,
Did you get this issue resolved?
I am facing the same issue. The code works fine for hotmail account but for the corporate office365 account it throws following error.
imaplib.error: login failed.

Any help is appreciated.

Thanks
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  IMAPLIB PR3636 0 1,659 Jul-21-2020, 11:19 AM
Last Post: PR3636

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020