Search code examples
permissionsgmail-apipublish-subscribegoogle-cloud-pubsub

Cant send Push notifications from Gmail API to Pub/Sub


I want to connect my Gmail API to Pub/Sub so I can analyze the mails that I get on an specific mail inbox.

I already configured my Pub/Sub topic to get messages. My Service account has Pub/Sub Publisher permissions and I sent individual messages to my Pub/Sub topic to make sure that my service account was working right with Pub/Sub and all correct. I added to my Domain-wide Delegation all the gmail API permissions I need to start a watch over my mail inbox. (https://www.googleapis.com/auth/gmail.modify, https://www.googleapis.com/auth/gmail.readonly, https://mail.google.com/, https://www.googleapis.com/auth/gmail.metadata). To make sure that my service account had permissions to connect to the Gmail API I sent mails between the organizations mails using the Gmail API library with Python.

I downloaded my credentials like 5 times too so I could be sure that the credentials were right.

Everything seems correct but when I run this code to start the watch:

credentials_path = 'key.json'

credentials = service_account.Credentials.from_service_account_file(
    credentials_path, subject='organization-mail@example.com',
    scopes=['https://www.googleapis.com/auth/gmail.modify']
)

service = build('gmail', 'v1', credentials=credentials)

request = {
        'labelIds': ['INBOX'],
        'topicName': 'projects/project-id/topics/topic-id',
        'labelFilterBehavior': 'INCLUDE'
    }
response = service.users().watch(userId='me', body=request).execute()

print('Watch Response:', response)

I get this error:

"Error sending test message to Cloud PubSub: User not authorized to perform this action.". Details: "[{'message': 'Error sending test message to Cloud PubSub: User not authorized to perform this action.', 'domain': 'global', 'reason': 'forbidden'}]">

I replaced all the information I introduced so my data is safe but asume that this code and response has all the right information.

I dont know what else to do D:

I just expect my organization mail to send push notifications when a new message is received in my inbox.


Solution

  • Google Cloud Permissions seems to be more complicated than I thought. I could solve it adding gmail-api-push@system.gserviceaccount.com with pub/sub publish permissions. But, in order to do this, I had to deactivate the "Domain restricted sharing" Organization Policy.