Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
441 views
in Technique[技术] by (71.8m points)

google apps script - 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?

question from:https://stackoverflow.com/questions/65843334/how-can-i-get-the-subject-of-an-email-gmail-python-api

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...