【问题标题】:How can I get the subject of an email gmail python API如何获取电子邮件 gmail python API 的主题
【发布时间】:2026-02-01 00:15:02
【问题描述】:
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”,也有标签收件箱。如何获取邮件的主题而不是正文?

【问题讨论】:

    标签: python-3.x google-apps-script gmail python-3.9


    【解决方案1】:

    看看message resourceMessagePartheader

    结构如下:

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

    和:

    也就是说,主题包含在标题中。

    您可以使用 Python 检索

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

    【讨论】:

    • 它输出这个错误:``` File "/Users/me/Coding/Gmail/getBodyInbox.py", line 77, in print(getbodyinbox()) File "/Users/ mel/Coding/Gmail/getBodyInbox.py",第 62 行,在 getbodyinbox subject= [i['value'] for i in headers if i["name"]=="Subject"] File "/Users/mel/Coding /Gmail/getBodyInbox.py",第 62 行,在 中 subject= [i['value'] for i in headers if i["name"]=="Subject"] TypeError: string indices must be integers `` `
    • 您能展示一下您是如何将它集成到您​​的其余代码中的吗?有关更完整的示例,请参阅 here
    • 我再次运行了代码,它自己修复了?现在好像还好。
    最近更新 更多