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
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.