【发布时间】:2020-09-28 14:31:15
【问题描述】:
我正在尝试编写一个 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!')
方法二:使用 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)
【问题讨论】:
-
请添加您目前尝试过的内容。
-
感谢@VenkataramanR,我已经编辑了我的问题,包括我尝试过的几种方法。
标签: python-3.x google-cloud-platform google-cloud-functions