简体   繁体   English

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

[英]Using python and imaplib4, how to download an email attachment and move into folder on desktop?

I'm using python and the imaplib4 module to find an email, download its attachment to an output directory. 我正在使用python和imaplib4模块查找电子邮件,将其附件下载到输出目录。 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 imaplib.IMAP4.error:命令FETCH在状态NONAUTH中非法,只允许在SELECTED状态

I think the issue is with the outputdir and the forward slash and backslash. 我认为问题在于outputdir和正斜杠和反斜杠。 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: 图片错误: 在此输入图像描述

Connect creates its own IMAP connection and returns it but you ignore it and pass a non connected IMAP session to downloadAttachmentsInEmail . Connect创建自己的IMAP连接并返回它但您忽略它并将未连接的IMAP会话传递给downloadAttachmentsInEmail

You should change your code to: 您应该将代码更改为:

# m = imaplib.IMAP4_SSL(server)     # useless
m = connect(server, user, password)
downloadAttachmentsInEmail(m, emailid, outputdir)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM