Python: how to get the subject of an email from gmail API

前端 未结 2 1069
轻奢々
轻奢々 2021-01-03 03:54

Using Gmail API, how can I retrieve the subject of an email?

I see it in the raw file but it\'s qui cumbersome to retrieve it, and I am sure there should be a way t

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-03 04:15

    Since this was the question I landed on, I just wanted to share what I found to solve my own issue.

    I am used to work with the email module that gives you a neat interface to interact with messages. In order to parse the message that the gmail api gives you, the following worked for me:

    import email
    import base64
    messageraw = service.users().messages().get(
        userId="me", 
        id=emails["id"], 
        format="raw", 
        metadataHeaders=None
    ).execute()
    email_message = email.message_from_bytes(
        base64.urlsafe_b64decode(messageraw['raw'])
    )
    

    You end up with an email.Message object and can access the metadata like email_message['from'].

提交回复
热议问题