在咱們開發完web系統後,一些特定的事件發生時,系統要自動發送相關郵件至管理員,運維人員和其餘相關人員。python標準庫中的smtplib包也能夠用在Flask程序中發送郵,但包裝了smtplib的flask-mail擴展能更好地和Flask集成。本篇文章簡單介紹一下如何使用flask-mail擴展發送郵件。html
網易郵箱服務器信息:(測試時使用的是網易郵箱地址做爲發件者,配置時使用下方信息)python
服務器名稱 | 服務器地址 | SSL協議端口號 | 非SSL協議端口號 |
---|---|---|---|
IMAP | imap.163.com | 993 | 143 |
SMTP | smtp.163.com | 465/994 | 25 |
POP3 | Pop.163.com | 995 | 110 |
linux
查看安裝狀況: pip show flask-mail, 信息以下,說明安裝成功git
Name: Flask-Mail Version: 0.9.1 Summary: Flask extension for sending email Home-page: https://github.com/rduplain/flask-mail Author: Dan Jacob Author-email: danjac354@gmail.com License: BSD Location: /anaconda3/envs/flaskdev/lib/python3.6/site-packages Requires: Flask, blinker Required-by:
發送郵件用的郵箱帳號、密碼沒有直接寫在腳本中,將帳號密碼添加到本地的環境變量,而後經過os模塊去調取。這麼作也是爲了安全起見。github
設置方法:web
mac os/linuxshell
export MAIL_USERNAME='你的郵箱帳號'flask
export MAIL_PASSWORD='客戶端受權密碼'windows
若是想永久有效,把上面兩句話加到配置文件中,mac(~/.bash_profile),linux(~/.bashrc)瀏覽器
windows
set MAIL_USERNAME='你的郵箱帳號'
set MAIL_PASSWORD='客戶端受權密碼'
若是想永久有效,右擊 個人電腦 -> 屬性 -> 高級系統設置 -> 環境變量,添加MAIL_USERNAME,MAIL_PASSWORD;有疑問的話能夠百度一下,很簡單。
注意事項:MAIL_PASSWORD,是客戶端受權密碼,和你常規登陸郵箱使用的密碼是兩回事兒,若是不知道本身的客戶端受權密碼,能夠百度搜索一下,具體的步驟就不在這裏寫了。
初步測試:
import os from flask import Flask from flask_script import Manager from flask_mail import Mail, Message app = Flask(__name__) app.config['MAIL_SERVER'] = 'smtp.163.com' app.config['MAIL_PORT'] = 25 app.config['MAIL_USE_TLS'] = True app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME') app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD') manager = Manager(app) mail = Mail(app) if __name__ == '__main__': manager.run()
終端操做:
(flaskdev) user@snow:~/codes/python$python debug.py shell >>> from flask_mail import Message >>> from debug import mail >>> msg = Message('Flask Test Mail', sender='發件人', recipients=['收件人1','收件人2']) >>> msg.body = '郵件內容' >>> msg.html = '<b>來自大師兄的問候</b>' >>> with app.app_context(): ... mail.send(msg) ... # Message參數說明: # 第一個參數:郵件主題 # 第二個參數:發件人郵箱帳號 # 第三個參數:收件人郵箱帳號(能夠寫一個或多個) # msg.body和msg.html是郵件正文
測試能夠發送成功:
腳本修改:
app.config['FLASKY_MAIL_SUBJECT_PREFIX'] = '[Flasky]' app.config['FLASKY_MAIL_SENDER'] = 'Flasky Admin <xxxxx@163.com>' app.config['FLASKY_ADMIN'] = os.environ.get('FLASKY_ADMIN') # 增長髮送郵件函數 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) mail.send(msg) # 修改視圖函數,條件知足(本例是有新用戶登陸系統時),自動觸發發送郵件 @app.route('/', methods=['GET', 'POST']) def index(): form = NameForm() if form.validate_on_submit(): user = User.query.filter_by(username=form.name.data).first() if user is None: user = User(username=form.name.data) db.session.add(user) session['known'] = False if app.config['FLASKY_ADMIN']: send_mail(app.config['FLASKY_ADMIN'], 'New User', 'mail/new_user', user=user) else: session['known'] = True session['name'] = form.name.data form.name.data = '' return redirect(url_for('index')) return render_template('index.html', form=form, name=session.get('name'), current_time = datetime.utcnow(), known=session.get('known', False))
終端運行程序,新用戶登陸:
(flaskdev) user@snow:~/GitHubCodes/learnFlask$python hello.py runserver -d * Serving Flask app "hello" (lazy loading) * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: on * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: 103-932-194 127.0.0.1 - - [18/Aug/2018 16:16:53] "GET / HTTP/1.1" 200 - 127.0.0.1 - - [18/Aug/2018 16:17:20] "POST / HTTP/1.1" 302 - 127.0.0.1 - - [18/Aug/2018 16:17:20] "GET / HTTP/1.1" 200 - 127.0.0.1 - - [18/Aug/2018 16:17:48] "POST / HTTP/1.1" 302 - 127.0.0.1 - - [18/Aug/2018 16:17:48] "GET / HTTP/1.1" 200 -
瀏覽器:
收郵箱:
以上就是關於使用flask-mail擴展發送郵件的實際操做
源碼參考地址:https://github.com/miguelgrinberg/flasky.git;git checkout 6a