2017-09-07 3 views
0

퀵 스타트 가이드에 포함 된 스크립트를 실행 한 후 초기 설정이 끝난 후 모든 것이 정상적으로 작동하는 것으로 보입니다. 그들이 포함 된 ListMessages 함수를 사용하려고 시도하고 사용하는 쿼리에 따라 웹에서 테스트 버전을 사용할 때와 다른 응답을받습니다.Gmail API - 일부 검색어에 메시지가 표시되지 않음

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

작품 잘 예를 들어, 그러나

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

내가 다시 어떤 메시지를받을 없다고에서 작동하지 않습니다.

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

나는 내 자격 증명을 삭제하고 아무 소용이 서로 다른 범위를 시도했습니다, 그래서 내 범위를이었다 어쩌면 생각 : 온라인 나는 마찬가지로이 중 하나가 작동하지 않습니다 (22) 메시지

을받을. while 루프 내에서 확인 반환 메시지를 만들 웹 사이트의 코드를하지 않는 복사 할 때

전체 스크립트

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) 

답변

0

아래에 포함

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