【问题标题】:How to read all mails using Gmail api efficiently?如何有效地使用 Gmail api 阅读所有邮件?
【发布时间】:2021-06-29 01:12:44
【问题描述】:

我正在尝试通过收件箱使用 Gmail API 过滤来阅读用户的所有邮件。但是要阅读 16k+ 封邮件大约需要 2 小时。有什么有效的方法吗?

now = datetime.now()

timestamp = math.floor(datetime.timestamp(now))

count = 0
while True:
    results = service.users().messages().list(maxResults=50,userId='me',q='in:inbox before:{}'.format(timestamp)).execute()
    messages = results.get('messages')
    EmailRecepit=[]
    if messages==None:
        break
    for msg in messages:
        print("Count",count)
        count+=1
        # Get the message from its id

        txt = service.users().messages().get(userId='me', id=msg['id']).execute()
        try:
            # Get value of 'payload' from dictionary 'txt'
            payload = txt['payload']
            headers = payload['headers']
            attachment = payload['parts']
            for header in headers:  # getting the Sender
                if header['name'] == 'From':
                    msg_from = header['value']
                    name=sender_name(msg_from)#Sender Name Not email
            for a in attachment:
                if a.get('filename') != '' and len(a.get('filename')) != 0:
                    document = a.get('filename')
            if count % 50==0:
                timestamp = math.floor(datetime.timestamp(parser.parse(headers['Date']))

        except socket.error as error:
            pass
        except:
            pass

【问题讨论】:

  • 您好 Anurodh,添加您正在尝试的代码的一部分...以便我们知道如何为您提供帮助。

标签: python oauth-2.0 gmail-api


【解决方案1】:

你执行的请求越少,你的代码效率就越高

因此,你应该修改请求

service.users().messages().list(maxResults=50,userId='me',q='in:inbox before:{}'.format(timestamp)).execute()

通过增加每个请求的最大结果数,例如

指定:maxResults=500

但是,请注意,在大量电子邮件上使用service.users().messages().get() 意味着大量请求,这不可避免地会使您的代码变慢。

考虑通过扩展q 查询来缩小使用service.users().messages().list 检索的结果的数量,并且只检索您真正感兴趣的电子邮件。例如:仅带有附件的电子邮件、仅来自某个发件人的电子邮件或带有某些主题行。

如果您必须检索所有 16k 多封电子邮件 - 加快代码速度的唯一方法是使用 batch requests

看看例如here 获取如何在 Python 中实现对 Gmail API 的批处理请求的示例。请注意,如果您执行的请求过多,使用批处理请求仍会导致 excedding quota

【讨论】:

    猜你喜欢
    • 2015-12-10
    • 2012-01-01
    • 2014-11-07
    • 2018-05-11
    • 2014-08-30
    • 1970-01-01
    • 1970-01-01
    • 2015-09-15
    • 2020-04-28
    相关资源
    最近更新 更多