Gmail推送通知Python API

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Gmail推送通知Python API相关的知识,希望对你有一定的参考价值。

我正在尝试通过推送通知API在我的Gmail帐户上收到新邮件。我有一个带有ssl证书的服务器,我已经在谷歌验证为我的,并添加到我的Pub / Sub项目:

#!/usr/bin/python3

import http.server
import array
import ssl

class CallbackHTTPServer(http.server.HTTPServer):
    def server_activate(self):
        http.server.HTTPServer.server_activate(self)


class HttpProcessor(http.server.BaseHTTPRequestHandler):
    def add_OK_plain_text_header(self):
        self.send_response(200)
        self.send_header('content-type','text/plain')
        self.end_headers()


    def do_GET(self):
        self.add_OK_plain_text_header()
        print("GOT GET REQUEST")
        self.wfile.write("OK".encode('utf-8'))


    def do_POST(self):
        self.add_OK_plain_text_header()
        print("GOT POST REQUEST")
        self.wfile.write("OK".encode('utf-8'))


def main():
    httpd = CallbackHTTPServer(('', 443), HttpProcessor)
    httpd.socket = ssl.wrap_socket(httpd.socket, certfile='./server.pem', server_side=True)
    httpd.serve_forever()


if __name__ == "__main__":
    main()

我还创建了一个主题和订阅推送通知到我的服务器地址(如here中所述)。我还按照here中的说明初始化了Gmail API,并运行了使用正确的historyId和到期响应的Gmail API观看请求。但即使我通过向我的主题发布消息手动创建它,我的服务器也不会获得任何更新:

#!/usr/bin/python

from __future__ import print_function
import httplib2
import os

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/gmail-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/gmail.readonly'
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.
    """
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   '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 main():
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('gmail', 'v1', http=http)

    request = {
      'labelIds': ['INBOX'],
      'topicName': 'projects/################/topics/#######'
    }
    print(service.users().watch(userId='me', body=request).execute())


if __name__ == '__main__':
    main()
答案

您是否已授予Grant关于您主题的发布权限? check out this link

或者读到这个:

授予您主题的发布权限Cloud Pub / Sub要求您授予Gmail权限,以便向您的主题发布通知。

为此,您需要向serviceAccount:gmail-api-push@system.gserviceaccount.com授予发布权限。您可以按照资源级访问控制说明使用Cloud Pub / Sub Developer Console权限界面执行此操作。

以上是关于Gmail推送通知Python API的主要内容,如果未能解决你的问题,请参考以下文章

Gmail API 推送通知速率限制究竟是啥意思?

收到来自 gmail users.watch API 的推送通知后如何阅读用户 gmail?

如何使用 Python imaplib 为 IMAP (Gmail) 启用推送通知?

Gmail-api 附带电子邮件时如何收到通知

仅在有新邮件到达时接收 Gmail 推送通知

我们可以使用云发布/订阅接收多个用户到同一推送端点的 gmail 推送通知吗