新的pythongmailapi只检索昨天的消息

2024-06-09 21:32:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在更新一些脚本到新的pythongmailapi。但是,我很困惑如何更新以下内容,以便只检索昨天的消息。谁能告诉我怎么做吗?在

我目前能看到的唯一方法是遍历所有消息,并且只解析那些具有正确时间范围的时间段的消息。然而,如果我有1000条信息,那就显得非常低效。必须有一种更有效的方法来做到这一点。在

from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools
import os
import httplib2
import email
from apiclient.http import BatchHttpRequest
import base64
from bs4 import BeautifulSoup
import re
import datetime

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

SCOPES = 'https://www.googleapis.com/auth/gmail.readonly'
CLIENT_SECRET_FILE = '/Users/sokser/Downloads/client_secret.json'
APPLICATION_NAME = 'Gmail API Python Quickstart'


def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'gmail-python-quickstart.json')

    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials

def visible(element):
    if element.parent.name in ['style', 'script', '[document]', 'head', 'title']:
        return False
    elif re.match('<!--.*-->', str(element)):
        return False
    return True

def main():
    """Shows basic usage of the Gmail API.

    Creates a Gmail API service object and outputs a list of label names
    of the user's Gmail account.
    """
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('gmail', 'v1', http=http)
    #Get yesterdays date and the epoch time
    yesterday = datetime.date.today() - datetime.timedelta(1)
    unix_time= int(yesterday.strftime("%s"))

    messages = []

    message = service.users().messages().list(userId='me').execute()
    for m in message['messages']:
        #service.users().messages().get(userId='me',id=m['id'],format='full')
        message = service.users().messages().get(userId='me',id=m['id'],format='raw').execute()
        epoch = int(message['internalDate'])/1000

        msg_str = str(base64.urlsafe_b64decode(message['raw'].encode('ASCII')),'utf-8')
        mime_msg = email.message_from_string(msg_str)
        #print(message['payload']['parts'][0]['parts'])
        #print()
        mytext = None
        for part in mime_msg.walk():
            mime_msg.get_payload()
            #print(part)
            #print()
            if part.get_content_type() == 'text/plain':
                soup = BeautifulSoup(part.get_payload(decode=True))
                texts = soup.findAll(text=True)
                visible_texts = filter(visible,texts)
                mytext = ". ".join(visible_texts)
            if part.get_content_type() == 'text/html' and not mytext:
                mytext = part.get_payload(decode=True)
        print(mytext)
        print()

if __name__ == '__main__':
    main()

Tags: thepathfromimportmessagegetifos
1条回答
网友
1楼 · 发布于 2024-06-09 21:32:28

您可以将查询传递给搜索日期范围内消息的messages.list方法。实际上,您可以使用任何query supported by Gmail's advanced search。在

你这样做,只会返回消息。在

message = service.users().messages().list(userId='me').execute()

但是可以通过传递q关键字参数和指定before:和{}关键字的查询来搜索昨天发送的消息。在

^{pr2}$

您也可以尝试对他们的GMail ^{} reference page。在

相关问题 更多 >