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)
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.