2017-09-07 3 views
0

Nahm das Skript, das in der Kurzanleitung enthalten war und nach der ersten Einrichtung schien alles in Ordnung zu sein. Versucht, die ListMessages-Funktion zu verwenden, die sie in den Dokumenten enthalten, und abhängig von der Abfrage, die ich verwende, erhalte ich eine andere Antwort als wenn ich die Testversion im Web verwende. Zum BeispielGmail API - Auflisten von Nachrichten funktioniert nicht mit einigen Abfragen

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

funktioniert gut, jedoch

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

funktioniert nicht, dass ich keine Nachrichten zurück empfangen. Online erhalte ich 22 Nachrichten

Ähnlich funktioniert dies nicht funktionieren:

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

Ich dachte, vielleicht war es mein Umfang so Ich habe meine Anmeldeinformationen zu löschen und Ausprobieren verschiedener Bereiche ohne Erfolg.

Voll Script enthalten unter

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:[email protected]_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) 

Antwort

0

Wenn Sie den Code Kopieren von der Website sicher Rückmeldungen machen nicht innerhalb der while-Schleife

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 
Verwandte Themen