使用python和imaplib4,如何下载电子邮件附件并移至桌面上的文件夹?

时间:2019-05-14 13:27:27

标签: python outlook imaplib

我正在使用python和imaplib4模块查找电子邮件,并将其附件下载到输出目录。我不断收到以下错误(我在下面附有错误图片):

  

imaplib.IMAP4.error:仅在NONAUTH状态下命令FETCH非法   在“已选择”状态下允许

我认为问题在于outputdir以及正斜杠和反斜杠。有人可以帮助解决吗?请参见下面的代码:

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)

错误图片:enter image description here

1 个答案:

答案 0 :(得分:0)

Connect创建自己的IMAP连接并返回该连接,但您将其忽略,并将未连接的IMAP会话传递给CoinType = float(input("What Type Of Coin Do You Want To Change Into? (1.00, 0.50, 0.20, 0.10, 0.05, 0.02, 0.01) - "))

您应该将代码更改为:

downloadAttachmentsInEmail