以下是一个使用Python和Google Cloud的示例代码,用于在App Engine上发送电子邮件。
首先,确保您的App Engine应用程序被授权发送电子邮件。在您的项目中的app.yaml
文件中添加以下内容:
runtime: python39
env_variables:
EMAIL_SENDER: your-email@example.com
EMAIL_RECIPIENT: recipient@example.com
接下来,创建一个包含发送电子邮件功能的Python文件,例如main.py
:
import os
from google.cloud import mail
def send_email(request):
email_sender = os.environ.get('EMAIL_SENDER')
email_recipient = os.environ.get('EMAIL_RECIPIENT')
message = mail.EmailMessage()
message.sender = email_sender
message.to = email_recipient
message.subject = 'Test Email'
message.body = 'This is a test email from App Engine.'
try:
mail.send(message)
return 'Email sent successfully.'
except Exception as e:
return f'Error sending email: {str(e)}'
在这个示例中,我们使用了Google Cloud的google.cloud.mail
模块来发送电子邮件。我们从环境变量中获取发送者和接收者的电子邮件地址。
最后,使用以下命令部署您的App Engine应用程序:
gcloud app deploy
确保您已经正确设置了Google Cloud SDK,并且已经登录到正确的Google Cloud项目中。
部署完成后,您可以使用以下命令在浏览器中查看发送电子邮件的结果:
gcloud app browse
如果您在发送电子邮件后没有收到它,请检查以下几个方面:
请注意,邮件可能需要一些时间才能被传递到接收者的邮箱中。如果问题仍然存在,请参考Google Cloud的文档,了解更多关于App Engine发送电子邮件的信息。