代码之家  ›  专栏  ›  技术社区  ›  sergi martinez

从Gmail获取电子邮件并将其写入文件的最快方式

  •  0
  • sergi martinez  · 技术社区  · 4 年前

    目前我有这个:

    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():
        """Shows basic usage of the Gmail API.
        Lists the user's Gmail labels.
        """
        creds = None
        # The file token.pickle stores the user's access and refresh tokens, and is
        # created automatically when the authorization flow completes for the first
        # time.
        if os.path.exists('token.pickle'):
            with open('token.pickle', 'rb') as token:
                creds = pickle.load(token)
        # If there are no (valid) credentials available, let the user log in.
        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(port=0)
            # Save the credentials for the next run
            with open('token.pickle', 'wb') as token:
                pickle.dump(creds, token)
    
        service = build('gmail', 'v1', credentials=creds)
    
        resultsMessages = service.users().messages().list(userId='me', labelIds=['INBOX']).execute()
        messages = resultsMessages.get('messages', [])
    
        f = open("output.txt", "a")
    
        message_count = int(input("How many messages do you want to write?"))
    
        if not messages:
            print("no messages found")
        else:
            print("messages:")
            for i, message in enumerate(messages[:message_count]):
                f.write("message "+ str(i))
                msg = service.users().messages().get(userId='me', id=message['id']).execute()
                headers = msg["payload"]["headers"]
                subject = [i['value'] for i in headers if i["name"] == "Subject"]
                f.write("subject: "+subject[0])
                f.write("\n")
        f.close()
    
    if __name__ == '__main__':
        main()
    

    msg = service.users().messages().get(userId='me', id=message['id']).execute()

    0 回复  |  直到 4 年前
        1
  •  2
  •   Linda Lawton - DaImTo    4 年前

    我只想知道是否有一种方法,以获得例如20个JSON格式的电子邮件,只需一个调用。

    如果你查看gmailapi的文档,你会发现只有一种方法可以返回正在发送的电子邮件的详细信息消息。获取. Message get将单个消息id作为参数,并返回有关该单个消息的信息。

    无法向发送多个消息ID消息。获取.

    如果你正在寻找一种减少网络流量的方法,你应该考虑 batching 允许您最多发送100个的请求消息。获取一个http请求。