python - 如何让 Userb 第一条消息给我?下面的代码有助于获取最新消息。我想要该用户的第一条消息给我

标签 python python-3.x gmail gmail-api google-api-python-client

如何让 Userb 向我发送第一条消息? 下面的代码有助于获取最新消息。 我想要该用户给我的第一条消息。

用户a是我 用户b是其他用户

我们想要用户 b 发送给用户 a 的第一条消息

我的代码获取userb最新消息。

Python 编码新手 有什么建议吗?

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

最佳答案

您似乎正在使用

搜索消息
response = service.users().messages().list(userId='usera@gmail.com',
                                           q='from:userb@gmail.com',
                                           pageToken=page_token).execute()

这是正确的。这应该将所有消息从 b 返回到 a(循环结束后)。

但是,如果您检查 API 文档 messages.listsearch syntax您会注意到无法对这些消息进行排序。为了找到最后一个,您必须将它们全部下载,然后在您的计算机上本地对它们进行排序。您可以使用 fields 最小化请求的数据参数,然后仅请求所需消息的完整内容。

关于python - 如何让 Userb 第一条消息给我?下面的代码有助于获取最新消息。我想要该用户的第一条消息给我,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54177173/

相关文章:

python - 在 make 文件中/从命令行执行 IPython 笔记本

python - 将 100% 的内核与多处理模块一起使用

php - 使用 PHPMailer 为 Gmail API 格式化 MIME 消息时如何发送到 BCC 地址?

html - 无法调试 Gmail Mobile 的电子邮件模板

python - 使用您自己的模块时有关硬编码变量的最佳实践问题

vba - 用于在 Gmail 中撰写带有附件的邮件的 URL

python - '|' 和 '<' 在 numpy 类型中意味着什么?

python - 使用谷歌应用引擎python从外部链接上传图像到谷歌云存储

python - 在两列之间单独对每一行进行排序

python - 将函数应用于 Pandas 数据框的列