簡體   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