1
votes

I'm trying to get new messages on my Gmail account via push notifications API. I have a server with ssl certificate that I already verified in Google as mine and add to my Pub/Sub project:

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

I also created a topic and a subscription for push notifications to my server address (as described in here). I also initialized Gmail API as described in here and have ran Gmail API watch request that responded with correct historyId and expiration. But my server doesn't get any updates even when I create them manually by publishing message to my topic:

#!/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()
1
Check if you have granted Gmail privileges to publish notifications to your topic, Cloud Pub/Sub requires it. Also double check every steps in this document, to see if you have missed anything. Hope this helps.Mr.Rebot
Yes I granted privileges to publish notifications to Gmail. I've done all the steps of the document you give.Edvard Davtyan

1 Answers

2
votes

Have you grant Grant publish rights on your topic yet? check out this link

or read this:

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:[email protected]. You can do this using the Cloud Pub/Sub Developer Console permissions interface following the resource-level access control instructions.