Gmail API - 列出的消息不适用于某些查询

时间:2017-09-07 15:44:32

标签: python gmail-api

使用快速入门指南中包含的脚本,在初始设置之后,一切似乎都正常。试图使用它们包含在文档中的ListMessages函数,并且根据我使用的查询,我收到的响应与在Web上使用测试版本时的响应不同。例如

messages = ListMessagesMatchingQuery(service, 'me', query=' from:-me')

工作得很好, 然而

messages = ListMessagesMatchingQuery(service, 'me', query='after:1504748301 from:-me')

不起作用,因为我没有收到任何消息。在线我收到了22条消息

同样,这也不起作用:

messages = ListMessagesMatchingQuery(service, 'me', query='is:unread from:-me')

我想也许这是我的范围所以我一直在删除我的凭据并尝试不同的范围无济于事。

下面包含完整脚本

from __future__ import print_function
import httplib2
import os

from apiclient import discovery
from apiclient import errors
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
import time
import base64
import email

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

# If modifying these scopes, delete your previously saved credentials
# in folder
SCOPES = [
    'https://mail.google.com/',
    #'https://www.googleapis.com/auth/userinfo.email',
    #'https://www.googleapis.com/auth/userinfo.profile',
    # Add other requested scopes.
]
CLIENT_SECRET_FILE = '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.
    """
    dir_path = os.path.dirname(os.path.realpath(__file__))
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)
    credential_path = os.path.join(dir_path,
                                   'gmail-python-quickstart.json')

    store = 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 GetMessage(service, user_id, msg_id):
  """Get a Message with given ID.

  Args:
    service: Authorized Gmail API service instance.
    user_id: User's email address. The special value "me"
    can be used to indicate the authenticated user.
    msg_id: The ID of the Message required.

  Returns:
    A Message.
  """
  try:
    message = service.users().messages().get(userId=user_id, id=msg_id).execute()

    print('Message snippet: %s' % message['snippet'])

    return message
  except errors.HttpError, error:
    print ('An error occurred: %s' % error)


def GetMimeMessage(service, user_id, msg_id):
  """Get a Message and use it to create a MIME Message.

  Args:
    service: Authorized Gmail API service instance.
    user_id: User's email address. The special value "me"
    can be used to indicate the authenticated user.
    msg_id: The ID of the Message required.

  Returns:
    A MIME Message, consisting of data from Message.
  """
  try:
    message = service.users().messages().get(userId=user_id, id=msg_id,
                                             format='raw').execute()

    print('Message snippet: %s' % message['snippet'])

    msg_str = base64.urlsafe_b64decode(message['raw'].encode('ASCII'))

    mime_msg = email.message_from_string(msg_str)

    return mime_msg
  except errors.HttpError, error:
    print('An error occurred: %s' % error)


def ListMessagesMatchingQuery(service, user_id, query=''):
  """List all Messages of the user's mailbox matching the query.

  Args:
    service: Authorized Gmail API service instance.
    user_id: User's email address. The special value "me"
    can be used to indicate the authenticated user.
    query: String used to filter messages returned.
    Eg.- 'from:user@some_domain.com' for Messages from a particular sender.

  Returns:
    List of Messages that match the criteria of the query. Note that the
    returned list contains Message IDs, you must use get with the
    appropriate ID to get the details of a Message.
  """
  try:
      response = service.users().messages().list(userId=user_id,
                                               q=query).execute()
      messages = []
      if 'messages' in response:
          messages.extend(response['messages'])

      while 'nextPageToken' in response:
          page_token = response['nextPageToken']
          response = service.users().messages().list(userId=user_id, q=query,
                                         pageToken=page_token).execute()
          messages.extend(response['messages'])
          return messages
  except errors.HttpError, error:
      print("An error occurred: %s" % error)



"""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)

results = service.users().labels().list(userId='me').execute()
labels = results.get('labels', [])

"""
if not labels:
    print('No labels found.')
else:
  print('Labels:')
  for label in labels:
    print(label['name'])
"""


messages = ListMessagesMatchingQuery(service, 'me', query='after:1504748301 from:-me')
print("Current epoch: " + str(int(time.time())))
for message in messages:
    #print(message)
    actual_message = GetMessage(service, 'me', message['id'])
    print("internal date: " + actual_message['internalDate'])
    print('Delivered-To: ' + actual_message['payload']['headers'][0]['value'])
    print("From: " + actual_message['payload']['headers'][-3]['value'])
    print("\n")

    time.sleep(5)

1 个答案:

答案 0 :(得分:0)

从网站复制代码时,请确保返回消息不在while循环中

try:
      response = service.users().messages().list(userId=user_id,
                                               q=query).execute()
      print(response)
      messages = []
      if 'messages' in response:
          messages.extend(response['messages'])

      while 'nextPageToken' in response:
          page_token = response['nextPageToken']
          response = service.users().messages().list(userId=user_id, q=query,
                                         pageToken=page_token).execute()

          messages.extend(response['messages'])
      return messages