繁体   English   中英

Python 脚本不会下载带有附件的 HTML 电子邮件

[英]Python script wont download HTML emails with attachments

我最近发布了Use python to download email attachments only based on Subject Answers from that post 让我看到我的脚本无法下载附件的原因是因为电子邮件中有 HTML 试图从中下载附件。 但是,我不确定如何让这个脚本工作。 它适用于从纯文本电子邮件下载附件,但在有 HTML 时无法正常工作。 有没有人在这里有任何建议,我的代码有问题吗? 请不要发布指向人们代码的其他链接,我已经查看了很多链接并尝试实现它们,当电子邮件中有 HTML 时,所有链接似乎都有类似的问题。 这是我的代码在下载附件时遇到问题的电子邮件的图片。 通过电子邮件发送我的代码正在尝试获取

 import imaplib
 import email

server = 'imap.gmail.com'
user = '*****@lhac.com'
password = '*******'
outputdir = 'C:\install files'
subject = 'testtttt' #subject line of the emails you want to download attachments from

def connect(server, user, password):
    m = imaplib.IMAP4_SSL(server)
    m.login(user, password)
    m.select()
    return m

def downloaAttachmentsInEmail(m, emailid, outputdir):
    resp, data = m.fetch(emailid, "(BODY.PEEK[])")
    email_body = data[0][1]
    mail = email.message_from_bytes(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))

#download attachments from all emails with a specified subject line
def downloadAttachments(subject):
    m = connect(server, user, password)
    m.select("Inbox")
    typ, msgs = m.search(None, '(SUBJECT "' + subject + '")')
    msgs = msgs[0].split()
    for emailid in msgs:
        downloaAttachmentsInEmail(m, emailid, outputdir)

downloadAttachments(subject)

以下是我得到的错误:

"C:/Users/gkidd/Documents/mailscript.py", line 24, in 
downloaAttachmentsInEmail open(outputdir + '/' + part.get_filename(), 'wb').write(part.get_payload(decode=True)) 
OSError: [Errno 22] Invalid argument: 'C:\\install files/testing_lhac.com__Advanced__lhac.com.csv
from imap_tools import MailBox

# get all attachments from INBOX and save them to files
with MailBox('imap.my.ru').login('acc', 'pwd', 'INBOX') as mailbox:
    for msg in mailbox.fetch():
        for att in msg.attachments:
            print(att.filename, att.content_type)
            with open('C:/1/{}'.format(att.filename), 'wb') as f:
                f.write(att.payload)

https://github.com/ikvk/imap_tools

暂无
暂无

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

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