GmailAPI 可以检索用户的邮件,但不能检索群组的邮件



我想用GmailAPI获得Group在GoogleWorkspace中使用的电子邮件信息。

目前,我能够通过以下代码获得用户在GoogleWorkspace中使用的邮件。但是,当我指定Group的电子邮件地址时,出现错误。

消息似乎未经验证。我分别从GoogleWorkspace控制台和GCP控制台确认了以下内容:

GoogleWorkspace

我在GoogleWorkspace组织中添加了一个GCP服务帐户。为添加的服务帐户设置范围(下面的范围)

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授予服务帐户主体的角色

Google Workspace Add-on Developer

顺便说一下,下面的代码正在获取组织中所有用户的电子邮件,但只有对于GROUP,这是一个错误。

python代码


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") 

主要("users@gmail.com"用户,我可以得到邮件列表。组,将导致错误

错误消息


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"]

这似乎是一个认证错误,但我想我已经授予了所有可能的权限给服务帐户。也许还有什么我没有做的,但我想不出还有什么我可以做的,所以你能告诉我吗?请。

这将列出从域

中的用户设置到组的电子邮件正如评论中的案例链接所提到的,你不能直接列出Group的电子邮件,因为这是谷歌API中仅有的两个与Group相关的API,没有与email相关的Group API,这里是文档。然而,我做了一些测试和修改你的代码,之后,它的工作:

首先,在我在Workspace帐户内配置域范围的委托之前,我得到了错误消息。您可以在这里看到步骤:

  • 帮助中心域范围委托
  • Google开发人员域范围委托

我创建了一个静态的电子邮件列表。您可以使用此文档作为指南,以获取该域中的所有电子邮件。

下面是示例代码:
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)

列出您的域上的用户以组的名义发送的电子邮件

使用下面的示例代码,您可以列出代表用户发送到组的电子邮件。

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)

相关内容

  • 没有找到相关文章

最新更新