大家好,我正在尝试使用GmailAPI打印来自发件人的特定电子邮件。我设法做了一些研究,并观看了一些关于如何打印发件人和主题的视频,但由于某种原因,我无法打印邮件的正文。我浏览了GmailAPI,没有发现任何有助于以文本形式打印正文的东西。
能帮我把邮件正文打印出来吗…
service = build('gmail', 'v1', credentials=creds)
results = service.users().messages().list(userId='me', labelIds=['INBOX'], q="from:specific email, is:unread").execute()
messages = results.get('messages', [])
if not messages:
print("You have no New Messages.")
else:
message_count = 0
for message in messages:
msg = service.users().messages().get(userId='me', id=message['id']).execute()
message_count= message_count + 1
email_data= msg['payload']['headers']
for values in email_data:
name = values["name"]
if name == "From":
from_name = values ["value"]
print(from_name)
subject= [j['value'] for j in email_data if j["name"]=="Subject"]
print(subject)
就像我说的,这段代码拉取特定的电子邮件并打印发件人,我缺少的主题是主体。
我尝试过遵循这个堆栈溢出中发布的内容:如何使用GmailAPI(python)检索整个邮件正文,但我无法让它工作
在您的脚本中,以下修改如何?
service = build("gmail", "v1", credentials=creds)
results = service.users().messages().list(userId="me", labelIds=["INBOX"], q="from:specific email, is:unread").execute()
messages = results.get("messages", [])
if not messages:
print("You have no New Messages.")
else:
message_count = 0
for message in messages:
msg = service.users().messages().get(userId="me", id=message["id"]).execute()
message_count = message_count + 1
email_data = msg["payload"]["headers"]
for values in email_data:
name = values["name"]
if name == "From":
from_name = values["value"]
print(from_name)
subject = [j["value"] for j in email_data if j["name"] == "Subject"]
print(subject)
# I added the below script.
for p in msg["payload"]["parts"]:
if p["mimeType"] in ["text/plain", "text/html"]:
data = base64.urlsafe_b64decode(p["body"]["data"]).decode("utf-8")
print(data)
>
在这种情况下,请添加import base64
。
运行此脚本时,将同时检索文本正文和超文本标记语言正文。例如,当您只想检索文本正文时,请将["text/平原","text/html"]中的if p["mimeType"]:修改为if p["mimeType"] == "text/平原":。