通过 Python Google Cloud Function 发送电子邮件的最佳方式是什么? [英] What's the best way to send an e-mail via Python Google Cloud Function?

查看:32
本文介绍了通过 Python Google Cloud Function 发送电子邮件的最佳方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to write a Python Google Cloud Function to send an automated e-mail to the same G-mail address at the same time every day (e.g. every day at 00:00). What's the easiest way to accomplish this? I couldn't find any online tutorials or guidance in the online documentation...Thanks in advance!

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

Here's what I've tried so far but neither approach seems to work (real e-mail addresses, passwords and API keys hidden for obvious reasons)

方法一:使用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!')

方法二:使用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)

推荐答案

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

The best way to send emails using a Cloud function is by using an Email third party service.

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

GCP offers discounts for Sendgrid and Mailjet these services must be enabled via GCP marketplace to apply for this offers.

sendgrid 的配置非常简单

The configuration with sendgrid is very easy

  1. GCP 市场(我使用免费计划,12K 邮件/月)
  2. 在 sendgrid 中创建 api 密钥
  3. 验证您的 sendgrid 帐户电子邮件(使用您收到的电子邮件)
  1. activate a plan on GCP marketplace ( I use free plan, 12K mails/month)
  2. Create an api key in sendgrid
  3. validate your sendgrid account email (use the email that you received)

在云功能方面,您需要创建可变环境sendgrid api 密钥.

In cloud functions side you need to create a variable environment with your fresh sendgrid api key.

EMAIL_API_KEY = 你很棒的 api 密钥

您可以部署以下示例代码

and you can deploy the following example code

requirements.txt:

requirements.txt:

sendgrid

*未指定安装最新可用版本

*without specify version to install latest available

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

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

To schedule your emails, you could use Cloud Scheduler.

  1. 创建服务帐户您的函数中的 href="https://cloud.google.com/functions/docs/securing/managing-access-iam#console-console" rel="noreferrer">functions.invoker 权限
  2. 创建新的 Cloud 调度程序作业
  3. 以 cron 格式指定频率.
  4. 指定 HTTP 作为目标类型.
  5. 像往常一样添加您的云函数和方法的 URL.
  6. 从 Auth 标头下拉列表中选择令牌 OIDC
  7. 在服务帐户文本框中添加服务帐户电子邮件.
  1. Create a service account with functions.invoker permission within your function
  2. Create new Cloud scheduler job
  3. Specify the frequency in cron format.
  4. Specify HTTP as the target type.
  5. Add the URL of your cloud function and method as always.
  6. Select the token OIDC from the Auth header dropdown
  7. Add the service account email in the Service account text box.

这篇关于通过 Python Google Cloud Function 发送电子邮件的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆