1

I want to get the email information used by Group in GoogleWorkspace with GmailAPI.

Currently, I am able to get the mail used by User in GoogleWorkspace with the following code. However, an error occurs when I specify the Group's email address.

The message seems to be unauthenticated. I have confirmed the following from GoogleWorkspace console and GCP console respectively.

GoogleWorkspace

I added a GCP service account in the GoogleWorkspace organization. Set up SCOPES for the added service account (SCOPES below)

http://www.googleapis.com/auth/gmail.readonly

http:///www.googleapis.com/auth/groups

http:///www.googleapis.com/auth/admin.directory.group.readonly

http://www.googleapis.com/auth/admin.directory.group.member.readonly

http://mail.google.com/

GCP

Roles granted to principals of service accounts

Google Workspace Add-on Developer

By the way, the following code is getting the emails of all Users in the organization, but only for GROUP it is an error.

python code



from pprint import pprint
from googleapiclient.discovery import build
from google.auth.transport.requests import Request
from google.oauth2.service_account import Credentials

def main(email):
    detail_li=[]
    cred = Credentials.from_service_account_file('Service_account_key.json')
    cred = cred.with_scopes(['https://www.googleapis.com/auth/gmail.readonly'])
    cred.refresh(Request())
    cred = cred.with_subject(email)
    gmail = build('gmail', 'v1', credentials=cred)
    results = gmail.users().messages().list(userId=email,maxResults=3).execute()
    for message in results["messages"]:
        row = {}
        row["ID"] = message["id"]

 MessageDetail=gmail.users().messages().get(userId=email,id=message["id"]).execute()
        detail_li.append(MessageDetail)
    pprint(f"detail_li: {detail_li}")

main("group@gmail.com") 

main("users@gmail.com") Users, I can get the mail list. Group, would cause an error

Error Message



RefreshError: ('unauthorized_client: Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.', {'error': 'unauthorized_client', 'error_description': 'Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.'})

13     gmail = build('gmail', 'v1', credentials=cred)
14 
---> 15     results = gmail.users().messages().list(userId=email,maxResults=3).execute()
16     messages = results.get('messages', [])
17    for message in results["messages"]

It seems to be an authentication error, but I think I have granted all possible permissions to the service account. Maybe there is something I have not done, but I can't think of anything more I can do, so could you please advise me? Please.

sami
  • 19
  • 3

1 Answers1

0

This is to list the emails set to the group from the users in the domain

As mentioned in the case link in the comments, you cannot list the emails of the Group directly since this are the only 2 APIs related to Groups in Google API, there is no Group API related to email here is the documentation. However, I made some tests and modifications to your code, after that it works:

First, I was getting the error message before I configure domain-wide delegation inside the Workspace account. You can see the steps here:

I made an static list of emails. You can use this documentation as a guide to get all the emails in the domain.

Here is the sample code:

from googleapiclient.discovery import build
from google.auth.transport.requests import Request
from google.oauth2.service_account import Credentials
from googleapiclient.errors import HttpError



emails = ['user1@domain.com', 'user2@domain.com', 'user3@domain.com']



def main(email):
    detail_li=[]
    cred = Credentials.from_service_account_file('Service_account_key.json')
    cred = cred.with_scopes(['https://mail.google.com/',
                             'https://www.googleapis.com/auth/gmail.modify'])
    cred.refresh(Request())
    cred = cred.with_subject(email)
    try:
        gmail = build('gmail', 'v1', credentials=cred)

        #add query to list emails to the group
        results = gmail.users().messages().list(
            userId='me',q='to:group@domain.com',maxResults=3
            ).execute()


        if not results.get("messages"):
            print("no emails to the group")
            return            

        else:
            for message in results["messages"]:
                row = {}
                row["ID"] = message["id"]
                print(row["ID"])

            MessageDetail=gmail.users().messages().get(userId=email,id=message["id"]).execute()
            detail_li.append(MessageDetail)
            print(f"detail_li: {detail_li}")

    except HttpError as error:
        # TODO(developer) - Handle errors from drive API.
        print(f'An error occurred: {error}')

def search_to_group(emails):
    for email in emails:
        print(f'Email use in the impersonation {email}')
        main(email)

search_to_group(emails)

List emails sent on behalf of the group from the users on your domain

With the following sample code you can list the emails sent to the group on behalf of the user.

from googleapiclient.discovery import build
from google.auth.transport.requests import Request
from google.oauth2.service_account import Credentials
from googleapiclient.errors import HttpError



emails = ['user1@domain.com', 'user2@domain.com', 'user3@domain.com']



def main(email):
    detail_li=[]
    cred = Credentials.from_service_account_file('Service_account_key.json')
    cred = cred.with_scopes(['https://mail.google.com/',
                             'https://www.googleapis.com/auth/gmail.modify'])
    cred.refresh(Request())
    cred = cred.with_subject(email)
    try:
        gmail = build('gmail', 'v1', credentials=cred)

        #add query to list emails to the group
        results = gmail.users().messages().list(
                userId='me',
                q='to:group@domain.com',
                maxResults=3,
                labelIds='SENT'
            ).execute()


        if not results.get("messages"):
            print("no emails sent from the group")
            return            

        else:
            for message in results["messages"]:
                row = {}
                row["ID"] = message["id"]
                print(row["ID"])

            MessageDetail=gmail.users().messages().get(userId=email,id=message["id"]).execute()
            detail_li.append(MessageDetail)
            print(f"detail_li: {detail_li}")

    except HttpError as error:
        # TODO(developer) - Handle errors from drive API.
        print(f'An error occurred: {error}')

def search_to_group(emails):
    for email in emails:
        print(f'Email use in the impersonation {email}')
        main(email)

search_to_group(emails)
Giselle Valladares
  • 2,075
  • 1
  • 4
  • 13