使用Python和Oauth身份验证的Gmail API发送自动电子邮件

发布于 2025-01-27 11:49:52 字数 514 浏览 4 评论 0原文

我有一个使用SendGrid API发送电子邮件的Python代码,但是现在我想迁移到Google以发送业务电子邮件。它还在Docker容器中运行。

我跟随 gmail python QuickStart 问题是,在尝试发送电子邮件时,它在日志以获取令牌等。

是否有办法在背景中完成授权,而无需任何其他交互或使用API​​密钥,就像SendGrid这样的API键以编程方式验证您的应用程序吗?

我是服务提供商,想发送电子邮件,例如重置密码链接,确认代码等。该代码部署在Linux主机上。我可以访问Workspace帐户,并且已经验证了我的域。

I have a Python code that was using SendGrid API to send emails, but now I want to migrate to Google in order to send business emails. It also runs in Docker containers.

I followed Gmail Python Quickstart in order to use Gmail API in my Python code and the problem is that when trying to send email, it shows an authorization link in Docker logs in order to get token, etc.

Is there a way to complete authorization in the background without any further interaction or use an API key just like SendGrid to programmatically authenticate your application?

I am a service provider and want to send emails such as reset password links, confirmation code, etc. automatically; the code is deployed on a Linux host. I have access to workspace account, and I already have verified my domain.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

凉世弥音 2025-02-03 11:49:52

教程您关注的是为安装的应用程序而设计的。因此,安装了appflow

它说明它位于文件的顶部。

桌面应用程序的授权凭证。要了解如何为桌面应用程序创建凭据,请参阅创建凭据。

这意味着,当您的代码运行时,它将弹出机器上的同意屏幕,在这种情况下,代码正在运行。

flow = InstalledAppFlow.from_client_secrets_file(
            'credentials.json', SCOPES)

您需要使用Web应用程序创建它,以便您的用户可以同意您的应用程序访问其数据和Gmail帐户。

自动发送电子邮件服务帐户选项。

您尚不清楚您正在发送电子邮件。当您使用发送网格时,这对我来说意味着这是某种自动化系统。这意味着您正在尝试代表您控制的Gmail帐户发送电子邮件。

在这种情况下,您通常需要使用服务帐户。服务帐户允许Google API之间的服务器与服务器交互。但是,服务帐户只有在这是Google Workspace Gmail帐户时才与Gmail一起使用,并且您可以设置域范围内的代表团

文档中有一个示例。只需将其更改为Gmail范围即可。关键点是 create_delegated 必须是您域上的用户。

from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

# Email of the Service Account
SERVICE_ACCOUNT_EMAIL = '<some-id>@developer.gserviceaccount.com'

# Path to the Service Account's Private Key file
SERVICE_ACCOUNT_PKCS12_FILE_PATH = '/path/to/<public_key_fingerprint>-privatekey.p12'

def create_directory_service(user_email):
    """Build and returns an Admin SDK Directory service object authorized with the service accounts
    that act on behalf of the given user.

    Arguments:
      user_email: The email of the user. Needs permissions to access the Admin APIs.
    Returns:
      Admin SDK directory service object.
    """

    credentials = ServiceAccountCredentials.from_p12_keyfile(
        SERVICE_ACCOUNT_EMAIL,
        SERVICE_ACCOUNT_PKCS12_FILE_PATH,
        'notasecret',
        scopes=['https://www.googleapis.com/auth/admin.directory.user'])

    credentials = credentials.create_delegated(user_email)

    return build('admin', 'directory_v1', credentials=credentials)

标准Gmail解决方案

您可以运行一次应用程序,然后将其放置在Docker容器中时,请确保您包含创建的 token.json 文件,这是包含凭据的文件授予申请访问您的帐户。

如果打开它,您会在其中找到一个访问令牌和刷新令牌。刷新令牌将使您的应用程序能够在需要时请求新的访问令牌。

The tutorial you are following is designed for an installed application. Hence the InstalledAppFlow.

It states it at the top of the file.

Authorization credentials for a desktop application. To learn how to create credentials for a desktop application, refer to Create credentials.

This means when your code runs it is going to pop up the consent screen on the machine the code is running on, in this instance Docker.

flow = InstalledAppFlow.from_client_secrets_file(
            'credentials.json', SCOPES)

You need to create it using a web application so that your users can consent to your application accessing their data and their Gmail account.

Automated send emails service account option.

You were not clear as who you are sending emails for. As you are using send grid, it implies to me this is some kind of automated system. Which would mean that you are trying to send emails on behalf of a Gmail account that you control.

In that case you would most often want to use a service account. Service accounts allow for server-to-server interaction between Google APIs. However, service accounts will only work with Gmail if this is a Google workspace Gmail account and you can set up domain-wide delegation.

There is an example in the documentation. Just change it to Gmail scopes. The key point is the create_delegated which must be a user on your domain.

from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

# Email of the Service Account
SERVICE_ACCOUNT_EMAIL = '<some-id>@developer.gserviceaccount.com'

# Path to the Service Account's Private Key file
SERVICE_ACCOUNT_PKCS12_FILE_PATH = '/path/to/<public_key_fingerprint>-privatekey.p12'

def create_directory_service(user_email):
    """Build and returns an Admin SDK Directory service object authorized with the service accounts
    that act on behalf of the given user.

    Arguments:
      user_email: The email of the user. Needs permissions to access the Admin APIs.
    Returns:
      Admin SDK directory service object.
    """

    credentials = ServiceAccountCredentials.from_p12_keyfile(
        SERVICE_ACCOUNT_EMAIL,
        SERVICE_ACCOUNT_PKCS12_FILE_PATH,
        'notasecret',
        scopes=['https://www.googleapis.com/auth/admin.directory.user'])

    credentials = credentials.create_delegated(user_email)

    return build('admin', 'directory_v1', credentials=credentials)

Standard Gmail solution

You can run your application once, and then when you place it in the Docker container, make sure that you include the token.json file that was created this is the file that contains the credentials that grant the application access to your account.

If you open it you will find an access token and a refresh token within. The refresh token will give your application the ability to request a new access token whenever it needs one.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文