1. 程式人生 > >Flask --(30)Flask 中郵件擴充套件的實現

Flask --(30)Flask 中郵件擴充套件的實現

郵件擴充套件

在開發過程中,很多應用程式都需要通過郵件提醒使用者,Flask的擴充套件包Flask-Mail通過包裝了Python內建的smtplib包,可以用在Flask程式中傳送郵件。

Flask-Mail連線到簡單郵件協議(Simple Mail Transfer Protocol,SMTP)伺服器,並把郵件交給伺服器傳送。

設定郵箱授權碼

在這裡插入圖片描述

如下示例,通過開啟 QQ 郵箱驗證 SMTP 服務設定,傳送郵件:

#coding:utf-8
from flask import Flask,render_template
from flask_mail import Mail, Message
from threading import Thread


app = Flask(__name__)
# 配置郵件:伺服器/埠/安全套接字層/郵箱名/授權碼
app.config['MAIL_SERVER'] = "smtp.126.com"
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = "
[email protected]
" app.config['MAIL_PASSWORD'] = "19940414" app.config['MAIL_DEFAULT_SENDER'] = 'FlaskAdmin<[email protected]>' mail = Mail(app) def async_send_email(app, msg): with app.app_context(): try: mail.send(msg) except Exception as e: print e def send_email_thread(subject, to, content): msg = Message(subject=subject, recipients=[to], body=content) thread = Thread(target=async_send_email,args=(app, msg)) thread.start() return thread @app.route('/') def index(): return '<a href="%s">傳送郵件</a>' % url_for('send_email') @app.route('/send_email') def send_email(): send_email_thread('我是郵件主題', to='
[email protected]
', content='我是郵件內容哈哈') return '傳送中...' if __name__ == '__main__': app.run()