0

I'm using python and the imaplib4 module to find an email, download its attachment to an output directory. I keep getting the following error (I attached a picture of the error below):

imaplib.IMAP4.error: command FETCH illegal in state NONAUTH, only allowed in states SELECTED

I think the issue is with the outputdir and the forward slash and backslash. Could anyone help to solve? See the code below:

import imaplib
import email
import datetime
# Connect to an IMAP server
def connect(server, user, password):
    m = imaplib.IMAP4_SSL(server)
    print("{0} Connecting to mailbox via IMAP...".format(datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S")))
    m.login(user, password)
    m.select()
    return m
# Download all attachment files for a given email
def downloadAttachmentsInEmail(m, emailid, outputdir):
    resp, data = m.fetch(emailid, "(BODY.PEEK[])")
    email_body = data[0][1]
    mail = email.message_from_string(email_body)
    if mail.get_content_maintype() != 'multipart':
        return
    for part in mail.walk():
        if part.get_content_maintype() != 'multipart' and part.get('Content-Disposition') is not None:
            open(outputdir + '/' + part.get_filename(), 'wb').write(part.get_payload(decode=True))
server= 'imap-mail.outlook.com'
user='myname@company.com'
password='thisisapassword'
emailid= 'attachmentemail@gmail.com'
outputdir=r'C:\Users\username\Desktop\imap4_folder'
m = imaplib.IMAP4_SSL(server)
connect(server, user, password)
downloadAttachmentsInEmail(m, emailid, outputdir)

Pic of the error: enter image description here

BrianBeing
  • 431
  • 2
  • 4
  • 12

1 Answers1

0

Connect creates its own IMAP connection and returns it but you ignore it and pass a non connected IMAP session to downloadAttachmentsInEmail.

You should change your code to:

# m = imaplib.IMAP4_SSL(server)     # useless
m = connect(server, user, password)
downloadAttachmentsInEmail(m, emailid, outputdir)
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
  • I made the changes you suggested. Would you please explain further, your suggestions did not seem to work. – BrianBeing May 14 '19 at 14:46
  • I hope the error to be different. If yes, you should ask a new question with this one as a reference, if not (if the error has not changed) just edit this question with the new details. – Serge Ballesta May 14 '19 at 15:02
  • Same error. How about you paste your whole code so the community can see? – BrianBeing May 14 '19 at 18:41