通过 Python Google Cloud Function 发送电子邮件的最佳方式是什么?

abg*_*020 6 python-3.x google-cloud-platform google-cloud-functions

我正在尝试编写一个 Python 谷歌云函数来在每天的同一时间(例如每天 00:00)向同一个 G-mail 地址发送自动电子邮件。实现这一目标的最简单方法是什么?我在在线文档中找不到任何在线教程或指导...提前致谢!

这是我迄今为止尝试过的方法,但两种方法似乎都不起作用(出于显而易见的原因隐藏了真实的电子邮件地址、密码和 API 密钥)

方法一:使用smtplib(函数体)

import smtplib

gmail_user = 'SenderEmailAddress@gmail.com'
gmail_password = 'SenderEmailPassword'

sent_from = gmail_user
to = ['RecipientEmailAddress@gmail.com']
subject = 'Test e-mail from Python'
body = 'Test e-mail body'

email_text = """\
From: %s
To: %s
Subject: %s

%s
""" % (sent_from, ", ".join(to), subject, body)

server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(gmail_user, gmail_password)
server.sendmail(sent_from, to, email_text)
server.close()
print('Email sent!')
Run Code Online (Sandbox Code Playgroud)

方法二:使用SendGrid API(函数体)

import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail

message = Mail(
    from_email='SenderEmailAddress@gmail.com',
    to_emails='RecipientEmailAddress@gmail.com',
    subject='Sending with Twilio SendGrid is Fun',
    html_content='<strong>and easy to do anywhere, even with Python</strong>')

try:
    sg = SendGridAPIClient("[SENDGRID API KEY]")
    #sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
    response = sg.send(message)
    print(response.status_code)
    print(response.body)
    print(response.headers)
except Exception as e:
    print(e.message)
Run Code Online (Sandbox Code Playgroud)

Jan*_*dez 14

使用云功能发送电子邮件的最佳方式是使用电子邮件第三方服务。

GCP 为 Sendgrid 和 Mailjet 提供折扣,这些服务必须通过 GCP 市场启用才能申请此优惠。

sendgrid 的配置非常简单

  1. GCP 市场上激活一个计划(我使用免费计划,12K 邮件/月)
  2. 在 sendgrid 中创建一个 api 密钥
  3. 验证您的 sendgrid 帐户电子邮件(使用您收到的电子邮件)

在云功能方面,您需要使用新的 sendgrid api 密钥创建一个可变环境

EMAIL_API_KEY = your awesome api key

您可以部署以下示例代码

要求.txt:

sendgrid
Run Code Online (Sandbox Code Playgroud)

*没有指定安装最新可用的版本

def email(request):
    import os
    from sendgrid import SendGridAPIClient
    from sendgrid.helpers.mail import Mail, Email
    from python_http_client.exceptions import HTTPError

    sg = SendGridAPIClient(os.environ['EMAIL_API_KEY'])

    html_content = "<p>Hello World!</p>"

    message = Mail(
        to_emails="[Destination]@email.com",
        from_email=Email('[YOUR]@gmail.com', "Your name"),
        subject="Hello world",
        html_content=html_content
        )
    message.add_bcc("[YOUR]@gmail.com")

    try:
        response = sg.send(message)
        return f"email.status_code={response.status_code}"
        #expected 202 Accepted

    except HTTPError as e:
        return e.message
Run Code Online (Sandbox Code Playgroud)

要安排您的电子邮件,您可以使用Cloud Scheduler

  1. 在您的函数中创建一个具有functions.invoker 权限的服务帐户
  2. 创建新的云调度程序作业
  3. 以 cron 格式指定频率。
  4. 指定 HTTP 作为目标类型。
  5. 像往常一样添加您的云函数和方法的 URL。
  6. 从 Auth 标头下拉列表中选择令牌 OIDC
  7. 在服务帐户文本框中添加服务帐户电子邮件。