[英]Read email in python 3.7 using imaplib with HTML body and attachments in the email
[英]How to get name of all email attachments of a particular mail using imaplib, python?
我正在嘗試獲取電子郵件的所有附件並為該特定郵件列出這些附件並將該列表保存在 JSON 文件中。 我被指示只使用imaplib
。
這是我用來提取郵件數據的函數,但是part.getfilename()
只返回一個附件,即使我發送了多個附件也是如此。
我想要的輸出是[attach1.xlss, attach2.xml, attch.csv]
之類的附件列表。 同樣,我只能使用imaplib
庫。 我也不想下載任何附件,所以請不要共享該代碼。 我嘗試了幾個網站,但找不到任何我可以使用的東西。
def get_body_and_attachments(msg):
email_body = None
filename = None
html_part = None
# if the email message is multipart
if msg.is_multipart():
# iterate over email parts
for part in msg.walk():
# extract content type of email
content_type = part.get_content_type()
content_disposition = str(part.get("Content-Disposition"))
try:
# get the email body
body = part.get_payload(decode=True).decode()
except:
pass
if content_type == "text/plain" and "attachment" not in content_disposition:
# print text/plain emails and skip attachments
email_body = body
elif "attachment" in content_disposition:
# download attachment
print(part.get_filename(), "helloooo")
filename = part.get_filename()
filename = filename
else:
# extract content type of email
content_type = msg.get_content_type()
# get the email body
body = msg.get_payload(decode=True).decode()
if content_type == "text/plain":
email_body = body
if content_type == "text/html":
html_part = body
return email_body, filename, html_part
很容易; 我只需要這樣做。
import re
# getting filenames
filenames = mailbox.uid('fetch', num, '(BODYSTRUCTURE)')[1][0]
filenames = re.findall('\("name".*?\)', str(filenames))
filenames = [filenames[i].split('" "')[1][:-2] for i in range(len(filenames))]
說明: mailbox.uid
將獲取特定 uid (num) 的消息(或郵件),並將返回一個字節字符串,其中包含與該消息相關的所有數據。
現在,我使用re.findall
查找所有附件名稱,然后清除返回值並將其保存為列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.