使用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)

谢谢你

原文由 Karthik S 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 672
1 个回答

我能找到的大多数答案都已过时。

这是一个 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:
            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)

# 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')
"""


对于自签名证书,请使用:

 ...
import ssl

context = ssl._create_unverified_context()
mail = Imbox(host, username=username, password=password, ssl=True, ssl_context=context, starttls=False)
...


笔记:

安全性较低的应用和您的 Google 帐号

为了帮助确保您的帐户安全,从 2022 年 5 月 30 日起,Google 不再支持使用要求您仅使用用户名和密码登录 Google 帐户的第三方应用程序或设备。

重要提示:此截止日期不适用于 Google Workspace 或 Google Cloud Identity 客户。这些客户的强制执行日期将在稍后的日期在 Workspace 博客上公布。

SRC


2022 年 8 月 22 日更新:您应该能够创建一个应用程序密码,以绕过“不太安全的应用程序”功能消失的问题。 (后者仍然适用于我的企业帐户,但必须为我的消费者帐户创建一个应用程序密码。)使用 imaplib,我可以使用应用程序密码登录。

原文由 Pedro Lobito 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题