猿问

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


慕田峪7331174
浏览 571回答 4
4回答

HUH函数

我能找到的大多数答案都已过时。这是一个用于从 Gmail 帐户下载附件的 python (>=3.6) 脚本。确保检查底部的过滤器选项并在您的谷歌帐户上启用不太安全的应用程序。import osfrom imbox import Imbox # pip install imboximport traceback# enable less secure apps on your google account# https://myaccount.google.com/lesssecureappshost = "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 inboxfor (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 inboxmessages = mail.messages()# Unread messagesmessages = mail.messages(unread=True)# Flagged messagesmessages = mail.messages(flagged=True)# Un-flagged messagesmessages = mail.messages(unflagged=True)# Messages sent FROMmessages = mail.messages(sent_from='sender@example.org')# Messages sent TOmessages = mail.messages(sent_to='receiver@example.org')# Messages received before specific datemessages = mail.messages(date__lt=datetime.date(2018, 7, 31))# Messages received after specific datemessages = mail.messages(date__gt=datetime.date(2018, 7, 30))# Messages received on a specific datemessages = mail.messages(date__on=datetime.date(2018, 7, 30))# Messages whose subjects contain a stringmessages = mail.messages(subject='Christmas')# Messages from a specific foldermessages = 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 博客上公布。SRC2022 年 8 月 22 日更新:您应该能够创建一个应用程序密码来解决“不太安全的应用程序”功能消失的问题。(后者仍然可以在我的企业帐户中使用,但必须为我的消费者帐户创建一个应用程序密码。)使用 imaplib,我可以使用应用程序密码登录。

小怪兽爱吃肉

我发现这对我来说最有效。只需在运行程序时保持您的前景打开,它就会提取具有特定主题行的未读邮件。import datetimeimport osimport win32com.clientpath = os.path.expanduser("~/Documents/xyz/folder_to_be_saved")  #location o file today = datetime.date.today()  # current date if you want currentoutlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")  #opens outlookinbox = outlook.GetDefaultFolder(6) messages = inbox.Itemsdef saveattachemnts(subject):    for message in messages:        if message.Subject == subject and message.Unread:        #if message.Unread:  #I usually use this because the subject line contains time and it varies over time. So I just use unread            # body_content = message.body            attachments = message.Attachments            attachment = attachments.Item(1)            for attachment in message.Attachments:                attachment.SaveAsFile(os.path.join(path, str(attachment)))                if message.Subject == subject and message.Unread:                    message.Unread = False                break                                saveattachemnts('EXAMPLE 1')saveattachemnts('EXAMPLE 2')

长风秋雁

from imap_tools import MailBox# get all attachments from INBOX and save them to fileswith 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

临摹微笑

我使用该解决方案从邮箱获取附件。由您决定,下载或保存到本地变量。另外请注意,我首先阅读了所有消息,因为大多数时候盒子都是空的:import imaplibimport emailclass MailBox:&nbsp; &nbsp; SMTP_SERVER = 'imap.gmail.com'&nbsp; &nbsp; SMTP_PORT = 993&nbsp; &nbsp; USER = '<user_email>'&nbsp; &nbsp; PASSWORD = '<password>'&nbsp; &nbsp; def __init__(self):&nbsp; &nbsp; &nbsp; &nbsp; self.imap = imaplib.IMAP4_SSL(host=self.SMTP_SERVER, port=self.SMTP_PORT)&nbsp; &nbsp; &nbsp; &nbsp; self.imap.login(self.USER, self.PASSWORD)&nbsp; &nbsp; def __enter__(self):&nbsp; &nbsp; &nbsp; &nbsp; self.emails = self._get_all_messages()&nbsp; &nbsp; def __exit__(self, exc_type, exc_value, exc_traceback):&nbsp; &nbsp; &nbsp; &nbsp; self.imap.close()&nbsp; &nbsp; &nbsp; &nbsp; self.imap.logout()&nbsp; &nbsp; def fetch_message(self, num=-1):&nbsp; &nbsp; &nbsp; &nbsp; _, data = self.imap.fetch(self.emails[num], '(RFC822)')&nbsp; &nbsp; &nbsp; &nbsp; _, bytes_data = data[0]&nbsp; &nbsp; &nbsp; &nbsp; email_message = email.message_from_bytes(bytes_data)&nbsp; &nbsp; &nbsp; &nbsp; return email_message&nbsp; &nbsp; def get_attachment(self, num=-1):&nbsp; &nbsp; &nbsp; &nbsp; for part in self.fetch_message(num).walk():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if part.get_content_maintype() == 'multipart' or part.get('Content-Disposition') is None:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if part.get_filename():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return part.get_payload(decode=True).decode('utf-8').strip()&nbsp; &nbsp; def _get_all_messages(self):&nbsp; &nbsp; &nbsp; &nbsp; self.imap.select('Inbox')&nbsp; &nbsp; &nbsp; &nbsp; status, data = self.imap.search(None, 'ALL')&nbsp; &nbsp; &nbsp; &nbsp; return data[0].split()
随时随地看视频慕课网APP

相关分类

Python
我要回答