Flask 学习 五 电子邮件

本文介绍如何在Flask应用中集成邮件发送功能,并通过配置SMTP服务器实现异步发送邮件。文章提供了详细的代码示例,包括环境变量设置及邮件模板渲染。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

pip install mail

 from flask_mail import Mail
# 邮件配置
app.config['MAIL_SERVER']='smtp.qq.com'
app.config['MAIL_PORT']=465
app.config['MAIL_USE_TLS']=True
app.config['MAIL_USERNAME']=os.environ.get('MAIL_USERNAME')
app.config['MAIL_PASSWORD']=os.environ.get('MAIL_PASSWORD')
mail =Mail(app)

# shell中发送电子邮件
Python hello.py shell
from flask.ext.mail import Message
from hello import mail
msg = Message('test subject', sender='you@example.com',recipients=['you@example.com'])
msg.body = 'text body'
msg.html = '<b>HTML</b> body'
with app.app_context():
    mail.send(msg)

程序集成发邮件功能

from threading import Thread
from flask_mail import Mail,Message
# 邮件配置
app.config['MAIL_SERVER']='smtp.qq.com'
app.config['MAIL_PORT']=465
app.config['MAIL_USE_TLS']=True
app.config['MAIL_USERNAME']=os.environ.get('MAIL_USERNAME')
app.config['MAIL_PASSWORD']=os.environ.get('MAIL_PASSWORD')
app.config['FLASKY_MAIL_SUBJECT_PREFIX']='[Flasky]'
app.config['FLASKY_MAIL_SENDER']='Flasky Admin <flasky@example.com>'#发件人
app.config['FLASKY_ADMIN'] = os.environ.get('FLASKY_ADMIN')  #收件人
mail =Mail(app)
def send_async_email(app,msg):
    with app.app_context():
        mail.send(msg)

def send_mail(to,subject,template,**kwargs):
    msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + subject,sender=app.config['FLASKY_MAIL_SENDER'],recipients=[to])
    msg.body=render_template(template + '.txt',**kwargs)
    msg.html = render_template(template + '.html', **kwargs)
    thr = Thread(target=send_async_email,args=[app,msg])
    thr.start()
    return thr

配置环境变量:set FLASKY_ADMIN=3153324684@qq.com

转载于:https://www.cnblogs.com/Erick-L/p/6882698.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值