0
では動作しませんクイックスタートガイドで、すべてが正常に動作しているように見えた初期セットアップの後に含まれたスクリプトを取りました。ドキュメントに含まれているListMessages関数を使用しようとしました。私が使用するクエリによっては、Web上でテスト版を使用したときとは異なる応答が返されます。GmailのAPI - リストのメッセージは、一部のクエリ
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:[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)