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

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

问题描述

我正在尝试编写Python Google Cloud Function,以便在每天的同一时间(例如每天的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)

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

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

推荐答案

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

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市场上激活计划.使用免费计划,每月12,000封邮件)
  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 = your awesome api key

您可以部署以下示例代码

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. >
  3. 创建新的Cloud Scheduler作业
  4. 以cron格式指定频率.
  5. 将HTTP指定为目标类型.
  6. 像往常一样添加您的云函数和方法的URL.
  7. 从Auth标头下拉列表中选择令牌OIDC
  8. 在服务帐户"文本框中添加服务帐户电子邮件.
  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天全站免登陆