gpt4 book ai didi

python - 带有 Flask Python 的亚马逊 SES

转载 作者:太空宇宙 更新时间:2023-11-03 13:10:48 24 4
gpt4 key购买 nike

我刚刚开始在 Flask 上使用 Python。我想了解使用 Amazon SES 从 Flask 发送电子邮件的最佳方式是什么?

我看过 boto ,但它是所有亚马逊服务的接口(interface)。我还看到了其他一些自定义示例。

在 Flask 中发送电子邮件的最佳、简单且高效的方法是什么?

谢谢。

最佳答案

我也遇到过类似情况。你应该Send Formatted Email Using the Amazon SES API .

您可以按照您的建议使用 boto。但这不像boto3那样更新。更多信息 here .

这是我成功完成的事情。

在您的 app.config 中包含以下键:

# Amazon Web Services credentials
AWS_ACCESS_KEY_ID = 'your access key id'
AWS_SECRET_ACCESS_KEY = 'your secret access key'

# Amazon Simple Email Service
SES_REGION_NAME = 'us-west-2' # change to match your region
SES_EMAIL_SOURCE = 'verified.email@example.com'

注意:电子邮件来源(发件人)必须是经过验证的电子邮件地址,如 SES 控制台中所配置。

然后,在您的代码中的某处,定义如下函数:

import boto3

def send_email(app, recipients, sender=None, subject='', text='', html=''):
ses = boto3.client(
'ses',
region_name=app.config['SES_REGION_NAME'],
aws_access_key_id=app.config['AWS_ACCESS_KEY_ID'],
aws_secret_access_key=app.config['AWS_SECRET_ACCESS_KEY']
)
if not sender:
sender = app.config['SES_EMAIL_SOURCE']

ses.send_email(
Source=sender,
Destination={'ToAddresses': recipients},
Message={
'Subject': {'Data': subject},
'Body': {
'Text': {'Data': text},
'Html': {'Data': html}
}
}
)

当然,如果您需要更复杂的消息,您可以在ses.send_email中添加更多参数。

然后你可以这样发送邮件:

recipients = ['john.doe@example.com']
subject = 'Thanks for registering'

# You can render the message using Jinja2
html = render_template('email.html', name='John Doe')

send_email(current_app,
recipients=recipients,
subject=subject,
html=html
)

改进:

您可以使用线程将电子邮件作为异步任务发送。这在 Miguel Grinberg 的 The Flask Mega-Tutorial,Part XI: Email Support 中有更好的解释。这实际上是我正在使用的。

或者,也许更好的是,您可以为此使用 Celery。但由于您在 Amazon 生态系统中,我会使用 SQS。

其他选项包括:

  • 您可以使用 Flask-Mail 并配置为通过 SMTP 接口(interface)访问 SES。这是一个更通用的解决方案(可以访问其他服务,不仅是 SES),但如果您坚持使用 Amazon,最好使用 API。
  • 有 Flask-SES 之类的选项,但我认为您不需要它。它基本上包装了 send_mail 函数。

关于python - 带有 Flask Python 的亚马逊 SES,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44062367/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com