Flask-mail

安装

  1. (venv) $ pip install flask-mail

配置信息

FLASK-MAIL SMTP服务器配置信息

配置 默认值 说明
MAIL_SERVER localhost 电子邮件服务器的主机名或ip地址
MAIL_PORT 25 电子邮件服务器的端口
MAIL_USE_TLS False 启动传输层安全(TLS translate layer security)协议
MAIL_USE_SSL False 启动安全套阶层(SSL secure sockets layer)协议
MAIL_USERNAME None 邮箱账号的用户名
MAIL_PASSWORD None 邮箱账户的密码

服务器名、地址与端口

服务器名称 服务器地址 SSL协议端口号 非SSL协议端口号
IMAP imap.163.com 993 143
SMTP smtp.163.com 465/994 25
smtp.126.com 465/994 25
POP3 Pop.163.com 995 110

配置使用

  1. import os
  2. # ...
  3. from flask_mail import Mail
  4. app.config['MAIL_SERVER'] = 'smtp.126.com'
  5. app.config['MAIL_PORT'] = 25
  6. # 开源作品,账号密码千万不要直接写入脚本
  7. app.config['MAIL_USERNAME'] = os.environ.get("mail_username")
  8. app.config['MAIL_PASSWORD'] = os.environ.get("mail_password")
  9. # Flask_Mail初始化
  10. mail = Mail(app)

一次性环境变量设置

  1. (venv) set MAIL_USERNAME = {username}

在python shell中发送

注意,Flask-Mail 中的 send() 函数使用 current_app,因此要在激活的程序上下文中执行。

  1. (venv) E:\blog>set FLASK_APP=hello.py
  2. from flask_mail import Message
  3. from hello import mail
  4. mail_title = "test mail"
  5. sender = "sender@126.com"
  6. recipients = ["recipient1@163.com"]
  7. msg = Message(mail_title, sender=sender, recipients=recipients)
  8. msg.body = "test body"
  9. msg.html = "<h1> html </h1>"
  10. with app.app_context():
  11. mail.send(msg)

image.png

在应用中集成功能

定义发邮件函数,在视图函数中调用

  1. #...
  2. # 配置邮件信息
  3. app.config['FLASKY_ADMIN'] = os.environ.get('FLASKY_ADMIN')
  4. app.config['FLASKY_MAIL_SUBJECT_PREFIX'] = '[Flasky]'
  5. app.config['FLASKY_MAIL_SENDER'] = 'Flasky Admin <xxx@163.com>'
  6. def send_main(to, subject, template, **kwargs):
  7. msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + subject,
  8. sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to])
  9. msg.body = render_template(template + '.txt', **kwargs)
  10. msg.html = render_template(template + '.html', **kwargs)
  11. mail.send(msg)
  12. @app.route('/', methods=['POST', 'GET'])
  13. def index():
  14. form = NameForm()
  15. if form.validate_on_submit():
  16. user = User.query.filter_by(username=form.name.data).first()
  17. if not user:
  18. user = User(username=form.name.data, password='123456')
  19. db.session.add(user)
  20. db.session.commit()
  21. session['known'] = False
  22. send_mail(form.name.data)
  23. else:
  24. session['known'] = True
  25. session['name'] = request.form.get("name")
  26. form.name.data = ""
  27. return redirect(url_for('index'))
  28. return render_template('index.html', form=form, name=session.get('name'))

异步发送邮件

在处理mail.send函数时停滞了几秒钟,为了在处理请求过程中避免不必要的延迟,将发送电子邮件函数移到后台线程中

  1. #...
  2. # 配置邮件信息
  3. app.config['FLASKY_ADMIN'] = os.environ.get('FLASKY_ADMIN')
  4. app.config['FLASKY_MAIL_SUBJECT_PREFIX'] = '[Flasky]'
  5. app.config['FLASKY_MAIL_SENDER'] = 'Flasky Admin <xxx@163.com>'
  6. def send_main(to, subject, template, **kwargs):
  7. msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + subject,
  8. sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to])
  9. msg.body = render_template(template + '.txt', **kwargs)
  10. msg.html = render_template(template + '.html', **kwargs)
  11. thr = Thread(target=send_async_email(), args=[app, msg])
  12. thr.start()
  13. return thr
  14. def send_async_email(app, msg):
  15. with app.app_context():
  16. mail.send(msg)
  17. @app.route('/', methods=['POST', 'GET'])
  18. def index():
  19. form = NameForm()
  20. if form.validate_on_submit():
  21. user = User.query.filter_by(username=form.name.data).first()
  22. if not user:
  23. user = User(username=form.name.data, password='123456')
  24. db.session.add(user)
  25. db.session.commit()
  26. session['known'] = False
  27. send_async_email()
  28. else:
  29. session['known'] = True
  30. session['name'] = request.form.get("name")
  31. form.name.data = ""
  32. return redirect(url_for('index'))
  33. return render_template('index.html', form=form, name=session.get('name'))