邮件发送
flask-mail
-
说明:专门用于邮件发送的扩展库,使用非常方便。
-
安装:
pip install flask-mail
-
使用:
from flask_mail import Mail, Message import os # 邮件发送配置,一定要放在创建Mail对象之前 app.config['MAIL_SERVER'] = '*******************' # 用户名 app.config['MAIL_USERNAME'] =‘ ******' # 授权码 app.config['MAIL_PASSWORD'] = os.getenv('MAIL_PASSWORD', '123456') # 创建发送邮件的对象 mail = Mail(app) @app.route('/send/') def send(): # 创建邮件消息对象 msg = Message('账户激活', recipients=['接受者邮箱'], sender=app.config['MAIL_USERNAME']) msg.html = '恭喜你,中奖了!!!' # 发送邮件 mail.send(msg) return '邮件已发送'
-
封装函数发送邮件
def send_mail(subject, to, template, *args, **kwargs): if isinstance(to, (list,turple): recipients = to elif isinstance(to, str): recipients = to.split(',') else: raise Exception('邮件接收者参数类型有误') # 创建邮件消息对象 msg = Message(subject, recipients=recipients, sender=app.config['MAIL_USERNAME']) # 将邮件模板渲染后作为邮件内容 msg.html = render_template(template, *args, **kwargs) # 发送邮件 mail.send(msg)
-
异步发送邮件
from flask import current_app # 异步发送邮件任务 def async_send_mail(app, msg): # 邮件发送必须在程序上下文 # 新的线程中没有上下文,因此需要手动创建 with app.app_context(): mail.send(msg) # 封装函数发送邮件 def send_mail(subject, to, template, *args, **kwargs): if isinstance(to, list): recipients = to elif isinstance(to, str): recipients = to.split(',') else: raise Exception('邮件接收者参数类型有误') # 创建邮件消息对象 msg = Message(subject, recipients=recipients, sender=app.config['MAIL_USERNAME']) # 将邮件模板渲染后作为邮件内容 msg.html = render_template(template, *args, **kwargs) # 异步发送邮件 # current_app是app的代理对象 # 根据代理对象current_app找到原始的app app = current_app._get_current_object() # 创建线程 thr = Thread(target=async_send_mail, args=(app, msg)) # 启动线程 thr.start() # 返回线程 return thr
-
QQ邮件发送额外配置:需要配置QQ邮箱开启smtp服务,然后设置授权码
# 邮箱端口 app.config['MAIL_PORT'] = 465 # 使用SSL(加密传输) app.config['MAIL_USE_SSL'] = True # 不是QQ邮箱的密码,而是授权码 app.config['MAIL_PASSWORD'] = '授权码'
环境变量
- windows:
- 设置:
set 环境变量名=值
- 获取:
set 环境变量名
- 设置:
- linux:
- 导出:
export 环境变量名=值
- 获取:
echo $环境变量名
- 导出:
- 代码:
os.getenv('环境变量名', '123456')