如何使用gmailapi在python中打印gmail的正文



大家好,我正在尝试使用Gmail API打印发件人的特定电子邮件。我已经做了一些研究,并观看了一些关于如何打印发件人和主题的视频,但由于某些原因,我无法打印邮件的正文。我查看了Gmail API,没有发现任何有助于以文本形式打印正文的内容。

如果有任何关于打印电子邮件正文的帮助,请。。。

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)

这个代码就像我说的,提取特定的电子邮件并打印发件人,而我所缺少的主题就是尸体。

我试着遵循这个stackoverflow中发布的内容:如何使用Gmail API(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

  • 运行此脚本时,将检索文本正文和HTML正文。例如,当您只想检索文本正文时,请将if p["mimeType"] in ["text/plain", "text/html"]:修改为if p["mimeType"] == "text/plain":

参考:

  • 方法:users.messages.get

相关内容

  • 没有找到相关文章

最新更新