获取所有用户ID的Gmail API

时间:2018-05-09 16:11:35

标签: python django gmail gmail-api google-api-python-client

我的任务是cout所有顶级发件人和用户电子邮件的最高接收者。 因此,计划是获取所有用户ID,将它们放入字典中,计算其数量并打印。

我尝试了这个但是它与INBOX标签(10 000+条消息)的效果不太好:

import base64
import email
import re
import operator

from googleapiclient import errors
from quickstart import service


def find(st):

    for i in range(0,len(st)):
        tmp = str(st[i])
        for j in range(0,len(tmp)):

            if tmp[j] == 'T' and tmp[j+1] == 'o' and tmp[j-1] == "'" and tmp[j+2] == "'":
                return i
        pass


def getTop(n):

    try:
        if n == 1:
            label_ids = "INBOX"
        else:
            label_ids = "SENT"

        user_id = "me"
        topers = service.users().labels().get(userId = user_id,id = label_ids).execute()

        count = topers['messagesTotal']
        print(count)
        topers = service.users().messages().list(userId = user_id, labelIds = label_ids).execute()
        arrId = []

        for i in range(0,count):
            arrId.append(topers['messages'][i]['id'])

        st = []
        for i in range(0,count):
            message = service.users().messages().get(userId=user_id,
                                                 id=arrId[i],
                                                 format = 'metadata').execute()
            head = message['payload']['headers']


            index = find(head)
            obval = head[index]['value']

            tmp = str(obval)
            tmp =tmp.split('<', 1)[-1]
            tmp = tmp.replace('>',"")
            st.append(tmp)
            cnt = 0
            mvalues = {}
        for mail in st:
            if not mail in mvalues:
                mvalues[mail] = 1
            else:
                mvalues[mail]+= 1


        sorted_values = sorted(mvalues.items(),key= operator.itemgetter(1))
        ln = len(sorted_values)
        for j in range(1,6):
            print(sorted_values[-j])
        pass
    except errors.HttpError as error:
        print('An error occurred: %s' % error)

我的问题是:获取所有这些用户电子邮件的最快和最正确的方法是什么? 如果我有很多消息,使用一段时间并且每次都提出请求并不是我猜的最佳方式。我试图解决这个问题大约4天。帮助

0 个答案:

没有答案