简体   繁体   English

Gmail api:如何使用 ID 获取收件人的电子邮件?

[英]Gmail api: How do I get the recipient's email using the ID?

I'm trying to get the recipient's email using the ID that I have retrieved.我正在尝试使用我检索到的 ID 获取收件人的电子邮件。 Below is the code.下面是代码。

messages = service.users().threads().list(userId='me', q='to:').execute().get('threads', [])
    for message in messages:
        #print(message)
        # print(dir(message))
        # print(message.get())
        if search in message['snippet']:
            #print(message['id'])
            message_id = message['id']
            # print(message_id)
            full_message = service.users().messages().get(userId='me', id=message_id, format="raw").execute()
            #print(full_message)
            msg_headers = full_message['payload']['headers']
            #print(msg_headers)
            msg_str = base64.urlsafe_b64decode(full_message['raw'].encode('ASCII'))
            mime_msg = email.message_from_bytes(msg_str)

            #print(mime_msg)

            x = re.findall('id=(\w+)\'', str(mime_msg))
            print(x)
            if len(x)> 0:
                return x[0]
                if msg_headers[x]['name'] == "To":
                    return msg_headers[x[0]]['value']
            else:
                return None

I get the error below.我收到以下错误。 How do I resolve this?我该如何解决?

Traceback (most recent call last):
  File "C:\test\test2.py", line 102, in <module>
    test = get_email_with("Test string")
  File "C:\test\test2.py", line 55, in get_email_with
    msg_headers = full_message['payload']['headers']
KeyError: 'payload'

The response from Gmail can be a little confusing. Gmail 的回复可能有点令人困惑。 You are on the right track with你在正确的轨道上

 msg_headers = full_message['payload']['headers']

One of the headers is called has a name of "Delivered-To" the value will be the email address that the mail was sent to.其中一个标题名为“Delivered-To”,该值将是邮件发送到的电子邮件地址。 So basiclly you need to search your msg_headers and find the one called "Delivered-To"所以基本上你需要搜索你的 msg_headers 并找到一个名为“Delivered-To”的

Unfortunately i am not a python dev i cant help you with the code.不幸的是,我不是 Python 开发人员,我无法为您提供代码帮助。 Python quickstart may give you some ideas on how to get the response out of the object. Python 快速入门可能会给你一些关于如何从对象中获取响应的想法。

response回复

 "payload": {
    "partId": "",
    "mimeType": "multipart/alternative",
    "filename": "",
    "headers": [
      {
        "name": "Delivered-To",
        "value": "xxxx@gmail.com"
      },

Issue:问题:

When the format is set to RAW , the field payload is not populated in the response.当格式设置为RAW ,不会在响应中填充字段payload

From the API official docs :来自 API 官方文档

RAW : Returns the full email message data with body content in the raw field as a base64url encoded string; RAW :以 base64url 编码字符串的形式返回原始字段中包含正文内容的完整电子邮件数据; the payload field is not used .不使用有效载荷字段

Solution:解决方案:

Use either FULL or METADATA as format when calling messages().get , instead of RAW (format is an option parameter, and if it is not specified, FULL is used as default).在调用messages().get时使用FULLMETADATA作为格式,而不是RAW (格式是一个选项参数,如果未指定,则默认使用FULL )。

So you should change this:所以你应该改变这个:

full_message = service.users().messages().get(userId='me', id=message_id, format="raw").execute()

To this:对此:

full_message = service.users().messages().get(userId='me', id=message_id).execute()

Or, alternatively, use format="raw" anyway and decode the base-64 encoded string full_message["raw"] .或者,无论如何,使用format="raw"并解码 base-64 编码的字符串full_message["raw"] Edit : In this case, though, you'd have to remove this line: msg_headers = full_message['payload']['headers'] .编辑:不过,在这种情况下,您必须删除这一行: msg_headers = full_message['payload']['headers']

Edit:编辑:

So, if you want to retrieve the recipient, you can do the following:因此,如果要检索收件人,可以执行以下操作:

full_message = service.users().messages().get(userId='me', id=message_id).execute()
msg_headers = full_message['payload']['headers']
for header in msg_headers:
    if header["name"] == "To":
        return header["value"]

Reference:参考:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 Gmail API 查找用于获取电子邮件的附件 ID? - How to Find the Attachment ID for Getting an Email Using the Gmail API? 如何使用LinkedIn的新api电话获取用户的电子邮件地址? - How do I get a user's email address using LinkedIn's new api call? 如何使用 gmail api 获取我的 gmail 帐户的每封邮件的正文? - How do I get body of every mails of my gmail account using gmail api? Using the gmail python API how can I get the most recent email that does not have a label “read” - Using the gmail python API how can I get the most recent email that does not have a label “read” 如何获取电子邮件 gmail python API 的发件人 - How can I get the sender of an email gmail python API 如何使用python向我的gmail发送电子邮件? - How do I send an email to my gmail using python? 我如何知道信封是否已送达收件人 email? - How do I know if a envelope have reach the recipient email? 在 ZA7F5F35426B92741117231B5638 中使用 Gmail API 使用消息 ID 搜索 email - Search for email using message-id using Gmail API in Python 如何使用 GMAIL API 更改电子邮件签名? - How to change email signature using GMAIL API? 如何使用Gmail Python API获取电子邮件发件人的电子邮件地址 - How to get the email-address of the sender of an email using Gmail Python API
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM