python - 使用 GmailAPI 在帐户设置中添加自动转发时出现问题

标签 python api email gmail-api

我想在我的应用程序中使用 gmailAPI 来使用自动转发功能,因为我是 API 的新手,所以我按照 python 快速入门指南中给出的步骤进行操作,然后我进行了如下操作

首先我去了:- https://developers.google.com/gmail/api/quickstart/python?authuser=0并按照那里的所有步骤打开 gmail API 并将 credentials.JSON 文件复制到工作目录并在系统上安装 python 包并复制代码。 然后我将范围编辑为:- https://www.googleapis.com/auth/gmail.settings.sharing 以便转发设置可用。 然后我使用以下方法编辑了代码:- https://developers.google.com/gmail/api/guides/forwarding_settings 最终代码如下所示:-

import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

SCOPES = ['https://www.googleapis.com/auth/gmail.settings.sharing']

def main():
    """Shows basic usage of the Gmail API.
    Lists the user's Gmail labels.
    """
    creds = None
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('gmail', 'v1', credentials=creds)
    address = { 'forwardingEmail': '<forwarding_mailid>' }
    result = service.users().settings().forwardingAddresses().\
        create(userId='me', body=address).execute()
    if result.get('verificationStatus') == 'accepted':
        body = {
            'emailAddress': result.get('forwardingEmail'),
            'enabled': True,
            'disposition': 'trash'
        }
        result = service.users().settings().\
            updateAutoForwarding(userId='me', body=body).execute()

if __name__ == '__main__':
    main()

它说转发邮件也应该被验证所以我在 gmail 的转发设置中验证了帐户中的“”(我也在从转发设置中删除邮件 ID 后测试了它)如:- https://developers.google.com/gmail/api/guides/forwarding_settings “您必须在使用前创建转发地址。在某些情况下,用户还必须验证地址的所有权。 如果 Gmail 要求用户验证转发地址,则该地址会返回,状态为待处理。验证消息会自动发送到目标电子邮件地址。电子邮件地址的所有者必须在使用前完成验证过程。 不需要验证的转发地址的验证状态为已接受。”

然后我在系统上运行脚本然后它要求登录所以我登录帐户然后脚本运行并且控制台产生了这个错误:-

googleapiclient.errors.HttpError: https://www.googleapis.com/gmail/v1/users/me/settings/forwardingAddresses?alt=json返回“访问仅限于已被委派全域权限的服务帐户”>

错误在这一行:- “创建(userId='我',body=address)。执行()”

在每个 senario 中,我在同一行遇到相同的错误,即在生成“结果”时。 我无法理解我在什么地方做错了什么,或者我是否忘记了中间的一些步骤。

最佳答案

您需要一个具有全域权限的服务帐户:

作为您收到的错误和 updateAutoForwarding明确说明,您需要使用具有全域权限的服务帐户才能更新自动转发设置:

This method is only available to service account clients that have been delegated domain-wide authority.

重要提示:您需要是域管理员才能向服务帐户授予域范围的权限。因此,如果您不是管理员,则无法通过 API 管理自动转发。

因此您必须创建一个服务帐户,授予它域范围的权限,并使用它来模拟一个普通帐户:

  • 检查 this有关什么是服务帐户的概述:特别是 this section如何创建它们和this one用于委派全域权限。

  • 成功设置服务帐户后,您必须更改在代码中构建凭据的方式,如下所示:

creds = service_account.Credentials.from_service_account_file('credentials.json', scopes=SCOPES)
creds = creds.with_subject('impersonated_account@your_domain.com')

其中 credentials.json 是为服务帐户下载的 JSON 文件,impersonated_account@your_domain.com 是您想要的电子邮件地址要模拟的服务帐户。

引用:

关于python - 使用 GmailAPI 在帐户设置中添加自动转发时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63168307/

相关文章:

python - Tensorflow tf.train.Saver 不保存所有变量

python - 如何找到哪些句子有最多的共同词?

python - 匹配特定模式之后的所有内容,除了空格直到下一个字母

ios - Facebook API 和 iOS

linux - 无法使用git send-email发送源码和补丁

python - 使用 SQLAlchemy 查询 SQL Server JSON 列

javascript - 如何使用 soundcloud Javascript SDK 播放私有(private)轨道

api - openapi中如何定义对象中的字段是唯一的?

php - "stream_socket_enable_crypto(): Peer certificate CN=` gains.nanosupercloud.com ' did not match expected CN=` smtp.sendgrid.net '"共享主机

java - 如何从jsp页面使用GMail SMTP服务器发送电子邮件?