chapter 2 - chapter 3 - chapter 4 - chapter 5 - 源碼
概念剖析-flask電子郵件操作
python 的郵件支持
- python 標準庫中的
smtplib
包可以用于發送電子郵件Flask-Mail
擴展包裝了smtplib
Flask-Mail
的電子郵件支持
- 安裝
pip install flask-mail
若不配置服務器,
Flask-Mail
會連接localhost
上的端口 25,發送郵件
Flask-Mail SMTP服務器的配置
配置 | 默認值 | 說明 |
---|---|---|
MAIL_SERVER |
localhost |
電子郵件主機名或IP地址 |
MAIL_PORT |
25 | 電子郵件服務器端口 |
MAIL_USE_TLS |
False |
啟用傳輸層安全協議(Transport Layer Security) |
MAIL_USE_SSL |
False |
啟用安全套接層(Secure Sockets Layer) |
MAIL_USERNAME |
None |
郵件賬戶的賬戶名 |
MAIL_PASSWORD |
None |
郵件賬戶的密碼 |
126郵箱的配置
Flask-mail測試和遇到的問題
聊聊HTTPS和SSL/TLS協議
126郵箱的服務器主機名smtp.126.com
,非SSL端口號25
,SSL端口號 465
,使用前需要配置客戶端授權密碼
from flask_mail import Mail, Message
...
# 設置郵件
app.config['MAIL_SERVER'] = 'smtp.126.com'
app.config['MAIL_PORT'] = 25
app.config['MAIL_USERNAME'] = os.environ.get('MAIL_126_USERNAME')
app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_126_PASSWORD')
# 導入郵件
mail = Mail(app)
...
# 路由 /mail>
@app.route('/mail')
def mail_test():
msg = Message('test subject', sender='發件人@126.com', recipients=['收件人列表@hust.edu.cn'])
msg.body = 'test body'
msg.html = '<b>HTML</b> body'
mail.send(msg)
return '<h1> hava send the message </h1>'
git add. git commit -m "flask mail demo"
,git tag 6a
模板渲染郵件
hello.py
文件中
from flask_mail import Mail, Message
...
# 設置郵件
app.config['MAIL_SERVER'] = 'smtp.126.com'
app.config['MAIL_PORT'] = 25
app.config['MAIL_USERNAME'] = os.environ.get('MAIL_126_USERNAME')
app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_126_PASSWORD')
# 設置管理員郵箱
app.config['FLASK_ADMIN'] = os.environ.get('FLASK_ADMIN')
# 設置 郵件主題前綴
app.config['FLASK_MAIL_SUBJECT_PREFIX'] = '[Flask]'
# 設置 發件人名稱,此處126郵箱要求發件人名稱與賬戶名一致,此處設置無效
app.config['FLASK_MAIL_SENDER'] = 'Flasky Admin <flasky@example.com>'
# 導入郵件
mail = Mail(app)
...
# 發件函數
def send_mail( to, subject, template, **kwargs):
msg = Message( app.config['FLASK_MAIL_SUBJECT_PREFIX'] + subject, sender = app.config['MAIL_USERNAME'], recipients=[to] )
# jinja2 同樣能夠渲染 txt 文件
msg.body = render_template( template + '.txt', **kwargs )
# jinja2 渲染 html 文件
msg.html = render_template( template + '.html', **kwargs )
mail.send(msg)
...
# 路由 index
@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)
# add 到 session
db.session.add(user)
session['known'] = False
# 發現新用戶,郵件通知管理員
if app.config['FLASK_ADMIN']:
send_mail(app.config['FLASK_ADMIN'], 'New User', 'mail/new_user', user=user )
else:
session['known'] = True
session['name'] = form.name.data
return redirect( url_for('index'))
return render_template('index.html', form=form, name=session.get('name'), known=session.get('known', False))
設置管理員郵箱環境變量,
set FLASK_ADMIN=xxx@xx.com
模板文件:'$templates/mail/new_user.txt
':User {{ user.username }} has joined.
模板文件:'$templates/mail/new_user.html
':User <b>{{ user.username }}</b> has joined.
git add. git commit -m "flask mail with template"
,git tag 6b
異步發送郵件
mail.send() 函數發送測試郵件時停滯了幾秒鐘,這個過程中瀏覽器無響應,為了避免不必要的延遲,將發送電子郵件的函數移到后臺線程中。
from threading import Thread
# 線程的執行函數
def send_async_email(app, msg):
# flsk 上下文的概念
with app.app_context():
mail.send(msg)
def send_mail( to, subject, template, **kwargs):
msg = Message( app.config['FLASK_MAIL_SUBJECT_PREFIX'] + subject, sender = app.config['MAIL_USERNAME'], recipients=[to] )
msg.body = render_template( template + '.txt', **kwargs )
msg.html = render_template( template + '.html', **kwargs )
# 創建發郵件線程
thr = Thread( target=send_async_email, args=[app,msg] )
thr.start()
# 為什么返回線程對象
return thr
當程序需要發送大量的電子郵件,可以將執行 send_asyc_email()
函數的操作發給 Celery
任務隊列
git add. git commit -m "flask sync mail with template"
,git tag 6c