Flask-Mail是一個(gè)對(duì)python smtplib進(jìn)行封裝以便集成到Flask提供發(fā)送郵件支持的模塊末患。在學(xué)習(xí)flask-mail遇到了兩個(gè)問(wèn)題,記錄下來(lái)以便以后查看。
flask-mail安裝
pip installl flask-mail
flask-mail的使用
代碼如下:
#!/usr/bin/env python
import flask import Flask
from flask_mail import Message, Mail #現(xiàn)在flask-mail改為flask_mail導(dǎo)入
app = Flask(__name__)
#app.config['MAIL_SERVER'] = '220.181.12.16'
app.config['MAIL_SERVER'] = 'smtp.163.com' # 這里用163郵件服務(wù)器
app.config['MAIL_PORT'] = 25
app.config['MAIL_USE_TLS'] = True # 啟用安全傳輸層協(xié)議
app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME') # 從系統(tǒng)環(huán)境變量加載用戶名和密碼
app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD')
mail = Mail(app)
# 創(chuàng)建郵件內(nèi)容
msg = Message('email subject',sender='sender-email-address@163.com',
recipients=['reciver-email-address@exmple.com'])
msg.body='郵件正文內(nèi)容'
# 發(fā)送郵件,沒有包含附件
with app.app_context():
mail.send(msg)
# 發(fā)送郵件,包含有附件
with app.app_context():
with app.open_resource('test.png') as f:
# msg.attach 郵件附件添加
# msg.attach("文件名", "類型", 讀取文件)
msg.attach('test.png','image/png',f.read())
mail.send(msg)
if __name__ == '__main__':
app.run()
執(zhí)行這段代碼遇到兩個(gè)問(wèn)題:
SMTP 530 認(rèn)證失敗皆愉,原因是開啟了smtp服務(wù),但是第三方郵件客戶端要使用授權(quán)碼登錄艇抠,所以要在163郵箱上設(shè)置幕庐,設(shè)置客戶端授權(quán)碼,并使用戶端授權(quán)碼作為第三方郵件客戶端的登錄密碼家淤,即是代碼中MAIL_PASSWORD的值翔脱。
SMTP error 554,在stackoverflow找到原因是DNS反向解析的問(wèn)題,解決方法是把['MAIL_SERVER'] = 'smtp.163.com替換成['MAIL_SERVER'] = '220.181.12.16'
SMTP error 554 is one of the more vague error codes, but is typically caused by the receiving server seeing something in the From or To headers that it doesn't like. This can be caused by a spam trap identifying your machine as a relay, or as a machine not trusted to send mail from your domain.
We ran into this problem recently when adding a new server to our array, and we fixed it by making sure that we had the correct reverse DNS lookup set up.