我正在使用以下代碼來檢索電子郵件的內容。從中我可以提取電子郵件的詳細資訊。
for i in range(messages, messages-N, -1):
# fetch the email message by ID
res, msg = imap.fetch(str(i), "(RFC822)")
for response in msg:
if isinstance(response, tuple):
# parse a bytes email into a message object
msg = email.message_from_bytes(response[1])
# decode the email subject
subject, encoding = decode_header(msg["Subject"])[0]
if isinstance(subject, bytes):
# if it's a bytes, decode to str
subject = subject.decode(encoding)
# decode email sender
From, encoding = decode_header(msg.get("From"))[0]
if isinstance(From, bytes):
From = From.decode(encoding)
Date, encoding = decode_header(msg["Date"])[0]
if isinstance(Date, bytes):
# if it's a bytes, decode to str
Date = Date.decode(encoding)
print("Subject:", subject)
print("From:", From)
print("Date:", Date)
# 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
print(body)
elif "attachment" in content_disposition:
# download attachment
print("Subject:","This Contains an Attachement")
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":
# print only text email parts
print(body)
if content_type == "text/html":
print("Content Type is HTML")
print("="*100)
但我需要找回,
print("Subject:", subject)
print("From:", From)
print("Date:", Date)
進入資料框。我應該如何改進這段代碼?我需要將整個輸出串列放在一個資料框中。
uj5u.com熱心網友回復:
如果您可以使用臨時檔案或任何型別的存盤,您可以將結果寫入該存盤并使用結果獲取所需的資料幀。
如果我們談論的電子郵件數量真的很小,您不必優化任何內容,只需將每一行連接到一個資料幀,但這是不好的做法,如果可能,您應該避免這種情況。當電子郵件量很大時,這會導致各種問題。首先,它會非常慢。將結果寫入 csv 或基于 sql 的資料庫,稍后您會感謝自己。
uj5u.com熱心網友回復:
我想我明白你的問題,subject是一個 str 而不是一個串列。您必須學習如何收集串列中的資料并將此串列傳遞給 Pandas DataFrame。然后你可以按照我的評論并使用 Pandas 創建一個 DataFrame。請檢查下面的粗略原型:
import pandas as pd
subject_list = []
from_list = []
date_list = []
for i in range(...):
# replace prints with list.append()
# print("Subject:", subject)
# print("From:", From)
# print("Date:", Date)
subject_list.append(subject)
from_list.append(From)
date_list.append(Date)
df = pd.DataFrame({"Subject": subject_list, "From": from_list, "Date": date_list})
print(df)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/331197.html
