如何获取电子邮件 gmail 的主题 python API

How can I get the subject of an email gmail python API

def getbodyinbox():
    service = build('gmail', 'v1', credentials=creds)
    label_name = "READ-BY-SCRIPT"
    label_id = 'Label_8507504117657095973'
    results = service.users().messages().list(
        userId='me', q="-label:"+label_name, maxResults=1).execute()
    messages = results.get('messages', [])
    body = []
    if not messages:
        body = "no messages"
        return body
    else:
        for message in messages:
            msg = service.users().messages().get(
                userId='me', id=message['id']).execute()
            labels = msg['labelIds']
            if "INBOX" in labels:
                headers = msg['payload']['headers']
                headers = str(headers)
                print(headers)
                if "class_ix" in headers:
                    body.append(msg['payload']['parts'])
                    if 'data' in body[0][0]['body']:
                        body = base64.urlsafe_b64decode(
                            body[0][0]['body']['data'])
                    elif 'data' in body[0][1]['body']:
                        body = base64.urlsafe_b64decode(
                            body[0][1]['body']['data'])
                    body = str(body)

                        
                    return body


print(getbodyinbox())

到目前为止,这是我的代码,其中获取凭据的部分和所有导入都已删除。它获取最近一封没有标签 'READ-BY-SCRIPT' 且标签为 INBOX 的电子邮件正文。我怎样才能得到电子邮件的主题而不是正文?

看看 message resource, MessagePart and header

结构如下:

  "payload": {
    "partId": string,
    "mimeType": string,
    "filename": string,
    "headers": [
      {
        "name": string,
        "value": string
      }
    ],

和:

所以,换句话说,主题包含在headers。

您可以在 Python 中检索

headers = msg['payload']['headers']
subject= [i['value'] for i in headers if i["name"]=="Subject"]