pip install flask-mail

    配置发邮件的相关信息

    1. import os
    2. # ...
    3. app.config['MAIL_SERVER'] = 'smtp.googlemail.com'
    4. app.config['MAIL_PORT'] = 587
    5. app.config['MAIL_USE_TLS'] = True
    6. app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME')
    7. app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD')

    编写发送邮件的函数,并且这里可以使用render_template渲染html。

    1. from flask_mail import Message
    2. app.config['FLASKY_MAIL_SUBJECT_PREFIX'] = '[Flasky]'
    3. app.config['FLASKY_MAIL_SENDER'] = 'Flasky Admin <flasky@example.com>'
    4. def send_email(to, subject, template, **kwargs):
    5. msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + subject,
    6. sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to])
    7. msg.body = render_template(template + '.txt', **kwargs)
    8. msg.html = render_template(template + '.html', **kwargs)
    9. mail.send(msg)

    编写异步发送邮件的函数

    1. from threading import Thread
    2. def send_async_email(app, msg):
    3. with app.app_context():
    4. mail.send(msg)
    5. def send_email(to, subject, template, **kwargs):
    6. msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + subject,
    7. sender=app.config['FLASKY_MAIL_SENDER'], recipients=[to])
    8. msg.body = render_template(template + '.txt', **kwargs)
    9. msg.html = render_template(template + '.html', **kwargs)
    10. thr = Thread(target=send_async_email, args=[app, msg])
    11. thr.start()
    12. return thr