用python从邮件中下载附件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用python从邮件中下载附件相关的知识,希望对你有一定的参考价值。

我有多封包含附件的邮件。我想下载未读邮件的附件,并且有一个特定的主题行。

例如,我收到一封主题为 "EXAMPLE "的邮件,并包含一个附件。因此,它将是下面的代码,我试过了,但它是不工作的 "这是一个Python代码

#Subject line can be "EXAMPLE" 
      for subject_line in lst_subject_line:    
             # typ, msgs = conn.search(None,'(UNSEEN SUBJECT "' + subject_line + '")')
             typ, msgs = conn.search(None,'("UNSEEN")')
             msgs = msgs[0].split()
             print(msgs)
             outputdir = "C:/Private/Python/Python/Source/Mail Reader"
             for email_id in msgs:
                    download_attachments_in_email(conn, email_id, outputdir)

谢谢你

答案

我可以找到的大多数答案都是过时的。这里有一个python(>=3.6)脚本来下载Gmail账户中的附件。确保你检查下面的过滤器选项。

import os
from imbox import Imbox # pip install imbox
import traceback

# enable less secure apps on your google account
# https://myaccount.google.com/lesssecureapps

host = "imap.gmail.com"
username = "username"
password = 'password'
download_folder = "/path/to/download/folder"

if not os.path.isdir(download_folder):
    os.makedirs(download_folder, exist_ok=True)
    
mail = Imbox(host, username=username, password=password, ssl=True, ssl_context=None, starttls=False)
messages = mail.messages() # defaults to inbox

for (uid, message) in messages:
    mail.mark_seen(uid) # optional, mark message as read

    for idx, attachment in enumerate(message.attachments):
        try:
            att_fn = attachment.get('filename')
            download_path = f"{download_folder}/{att_fn}"
            print(download_path)
            with open(download_path, "wb") as fp:
                fp.write(attachment.get('content').read())
        except:
            pass
            print(traceback.print_exc())

mail.logout()


"""
Available Message filters: 

# Gets all messages from the inbox
messages = mail.messages()

# Unread messages
messages = mail.messages(unread=True)

# Flagged messages
messages = mail.messages(flagged=True)

# Un-flagged messages
messages = mail.messages(unflagged=True)

# Flagged messages
messages = mail.messages(flagged=True)

# Un-flagged messages
messages = mail.messages(unflagged=True)

# Messages sent FROM
messages = mail.messages(sent_from='sender@example.org')

# Messages sent TO
messages = mail.messages(sent_to='receiver@example.org')

# Messages received before specific date
messages = mail.messages(date__lt=datetime.date(2018, 7, 31))

# Messages received after specific date
messages = mail.messages(date__gt=datetime.date(2018, 7, 30))

# Messages received on a specific date
messages = mail.messages(date__on=datetime.date(2018, 7, 30))

# Messages whose subjects contain a string
messages = mail.messages(subject='Christmas')

# Messages from a specific folder
messages = mail.messages(folder='Social')
"""
另一答案
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.comikvkimap_tools。

以上是关于用python从邮件中下载附件的主要内容,如果未能解决你的问题,请参考以下文章

使用Python从邮件中下载附件和提取元数据

用python实现自动发邮件的功能

python实现电子邮件附件指定时间段,批量下载以及C#小程序集成实现

VBA 使用多标准从 Outlook 下载电子邮件附件

如何使用 Python 从电子邮件内容中获取附加的 eml 文件?

python实现邮件接收附件下载操作