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

jobtbby3  于 2022-12-01  发布在  Python
关注(0)|答案(1)|浏览(107)

大家好,我正在尝试使用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:How to retrieve the whole message body using Gmail API (python)但我无法让它工作

fwzugrvs

fwzugrvs1#

在您的脚本中,如何进行以下修改?

修改的脚本:

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":

参考:

相关问题