Search code examples
python-3.xgoogle-apps-scriptgmailpython-3.9

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())

This is my code so far with the part that gets the credentials and all of the imports removed. It gets the body of the most recent email without a label 'READ-BY-SCRIPT' that also has the label INBOX. How can I get the subject of the email instead of the body?


Solution

  • Have a look at the message resource, MessagePart and header

    The structure is the following:

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

    and:

    enter image description here

    So, in other words, the subject is contained in the headers.

    You can retrieve in Python with

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