代码之家  ›  专栏  ›  技术社区  ›  MagTun

Python:如何从gmailapi获取邮件主题

  •  0
  • MagTun  · 技术社区  · 5 年前

    使用Gmail API,如何检索电子邮件的主题?

    我在原始文件中看到了它,但是检索它非常麻烦,我确信应该有一种方法可以直接通过API来完成它。

    messageraw= service.users().messages().get(userId="me", id=emails["id"], format="raw", metadataHeaders=None).execute()
    

    这是同一个问题 one 但它已经很接近了,所以我不能发布比提议的更好的答案。

    1 回复  |  直到 5 年前
        1
  •  8
  •   MagTun    5 年前

    answer headers payload

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

    但如果你使用 format="raw format="full" .

    # source  = https://developers.google.com/gmail/api/quickstart/python?authuser=2
    
    
    # connect to gmail api 
    from __future__ import print_function
    import pickle
    import os.path
    from googleapiclient.discovery import build
    from google_auth_oauthlib.flow import InstalledAppFlow
    from google.auth.transport.requests import Request
    
    
    # If modifying these scopes, delete the file token.pickle.
    SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
    
    
    def main():
    
        # create the credential the first time and save it in token.pickle
        creds = None
        if os.path.exists('token.pickle'):
            with open('token.pickle', 'rb') as token:
                creds = pickle.load(token)
        if not creds or not creds.valid:
            if creds and creds.expired and creds.refresh_token:
                creds.refresh(Request())
            else:
                flow = InstalledAppFlow.from_client_secrets_file(
                    'credentials.json', SCOPES)
                creds = flow.run_local_server()
            with open('token.pickle', 'wb') as token:
                pickle.dump(creds, token)
    
        #create the service 
        service = build('gmail', 'v1', credentials=creds)
    
        #*************************************
        # ressources for *get* email 
        # https://developers.google.com/resources/api-libraries/documentation/gmail/v1/python/latest/gmail_v1.users.messages.html#get
        # code example for decode https://developers.google.com/gmail/api/v1/reference/users/messages/get 
        #*************************************
    
        messageheader= service.users().messages().get(userId="me", id=emails["id"], format="full", metadataHeaders=None).execute()
        # print(messageheader)
        headers=messageheader["payload"]["headers"]
        subject= [i['value'] for i in headers if i["name"]=="Subject"]
        print(subject)  
    
    if __name__ == '__main__':
        main()
    
        2
  •  6
  •   António Ribeiro    4 年前

    因为这是我遇到的问题,我只想分享我发现的解决我自己问题的方法。

    我习惯于和 email

    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'])
    )
    

    你最终得到一个 email.Message email_message['from'] .