[英]Amazon SES with Flask Python
我剛開始在 Flask 上使用 Python。 我想了解使用 Amazon SES 從 Flask 發送電子郵件的最佳方式是什么?
我見過boto ,但它是所有亞馬遜服務的接口。 我也看過其他一些自定義示例。
在 Flask 中發送電子郵件的最佳、簡單和有效的方式是什么?
謝謝。
我也有類似的情況。 您應該使用 Amazon SES API 發送格式化電子郵件。
您可以按照您的建議使用 boto。 但這並不像 boto3 那樣更新。 更多信息在這里。
這是我成功完成的工作。
在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。 但由於您在亞馬遜生態系統中,我會使用 SQS。
其他選項包括:
send_mail
函數。我也剛看到這個很棒的教程(寫於 2020 年),它詳細解釋了如何創建一個與 Amazon SES 集成的簡單 Flask 應用程序:
https://qxf2.com/blog/sending-email-through-amazon-ses-with-flask-app/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.