gpt4 book ai didi

python - Gmail 推送通知 Python API

转载 作者:太空宇宙 更新时间:2023-11-03 13:22:16 25 4
gpt4 key购买 nike

我正在尝试通过推送通知 API 在我的 Gmail 帐户上接收新邮件。我有一个带有 ssl 证书的服务器,我已经在 Google 中验证了它是我的,并将其添加到我的 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。并运行了 Gmail API 监视请求,该请求以正确的 historyId 和过期时间响应。但是即使我通过向我的主题发布消息手动创建它们,我的服务器也没有得到任何更新:

#!/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

或者阅读这个:

Grant publish rights on your topic Cloud Pub/Sub requires that you grant Gmail privileges to publish notifications to your topic.

To do this, you need to grant publish privileges to serviceAccount:gmail-api-push@system.gserviceaccount.com. You can do this using the Cloud Pub/Sub Developer Console permissions interface following the resource-level access control instructions.

关于python - Gmail 推送通知 Python API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47122337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com