如何将Userb的第一条消息发送给我? 下面的代码有助于获取最新消息。 我想要该用户的第一个消息给我。
用户a是我 用户b是其他用户
我们希望用户b向用户a发送的第一条消息
我的代码获取userb最新消息。
pythoon编码新手 有什么建议吗?
from __future__ import print_function
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
from apiclient import errors
import base64
import email
from pampy import match, _
# If modifying these scopes, delete the file token.json.
SCOPES = 'https://www.googleapis.com/auth/gmail.readonly'
def main():
"""Shows basic usage of the Gmail API.
Lists the user's Gmail labels.
"""
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
store = file.Storage('token.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('gmail', 'v1', http=creds.authorize(Http()))
#print(service.users().execute())
# Call the Gmail API
results = service.users().labels().list(userId='me').execute()
#print(results)
labels = results.get('labels', [])
if not labels:
print('No labels found.')
else:
print('Labels:')
for label in labels:
print(label['name'])
response = service.users().messages().list(userId='usera@gmail.com',
q='from:userb@gmail.com').execute()
#print(response['messages'])
#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='usera@gmail.com', q='from:userb@gmail.com',
pageToken=page_token).execute()
messages.extend(response['messages'])
message = service.users().messages().get(userId='usera@gmail.com', id=messages[0]['id'],
format='raw').execute()
print('Message snippet: %s' % message['snippet'])
#print(base64.urlsafe_b64decode(message['raw'].encode('ASCII')))
msg_str = base64.urlsafe_b64decode(message['raw'].encode('ASCII'))
mime_msg = email.message_from_string(str(msg_str))
print(mime_msg)
if __name__ == '__main__':
main()
答案 0 :(得分:0)
您似乎正在使用
搜索邮件response = service.users().messages().list(userId='usera@gmail.com',
q='from:userb@gmail.com',
pageToken=page_token).execute()
这是正确的。这应该将所有消息从b返回到a(在循环完成之后)。
但是,如果您查看messages.list和search syntax的API文档,则会发现无法对这些消息进行排序。为了找到最后一个,您必须全部下载它们,然后在计算机上本地对其进行排序。您可以使用fields
参数来最小化所请求的数据,然后仅请求所需消息的全部内容。