Retrieve attachment file(csv) from outlook using python imap

i am trying to retrieve an attachment from email on outlook and download that attachment which is a csv file to a path on my local computer.

here is a sample of my code which i took from here

import imaplib
import base64
import os
import email
from datetime import datetime

mail = imaplib.IMAP4('outlook.office365.com',993)
mail.login('email','password')
mail.select('Inbox')

type, data = mail.search(None, 'ALL')
mail_ids = data[0]
id_list = mail_ids.split()

for num in data[0].split():
    typ, data = mail.fetch(b'1', '(RFC822)' )
    raw_email = data[0][1]
# converts byte literal to string removing b''
    raw_email_string = raw_email.decode('utf-8')
    email_message = email.message_from_string(raw_email_string)
# downloading attachments
    for part in email_message.walk():
        # this part comes from the snipped I don't understand yet... 
        if part.get_content_maintype() == 'multipart':
            continue
        if part.get('Content-Disposition') is None:
            continue
        fileName = part.get_filename()
        if bool(fileName):
            filePath = os.path.join(mypath, fileName)
            if not os.path.isfile(filePath) :
                fp = open(filePath, 'wb')
                fp.write(part.get_payload(decode=True))
                fp.close()
            subject = str(email_message).split("Subject: ", 1)[1].split("\nTo:", 1)[0]
             print('Downloaded "{file}" from email titled "{subject}" with UID {uid}.'.format(file=fileName, subject=subject, uid=latest_email_uid.decode('utf-8')))

however i keep having an error of 'abort: socket error: EOF' when executing this part:

mail = imaplib.IMAP4('outlook.office365.com',993)
mail.login('email','password')
mail.select('Inbox')

so while looking out for this error on stack, i found an other way to write it:

while True:
    mail = imaplib.IMAP4('outlook.office365.com',993)
    r, d = mail.login('email','password')
    assert r == 'OK', 'login failed'
    try:
        mail.select('Inbox')
    except imap.abort as e:
        continue
    imap.logout()
    break

but still having the same error of abort.

for better practice, i am trying to avoid the while statement also.

can anyone help me out?

im trying to login and download the file from the specific sender and with a subject in outlook using python 3>

thanks in advance.


You need to use SSL. You are trying to connect to an encrypted port with a plaintext session.

Make sure you are using the SSL version of the IMAP object:

mail = imaplib.IMAP4_SSL('outlook.office365.com',993)

The server closes the connection on you because it doesn’t receive an SSL negotiation.