1.單線程的發送
# encoding: utf-8
import sys
from flask import Flask, url_for
# Mail可以看作是郵件的用戶端
# Message代表目前要發出的資訊,主題/内容/接收人都封裝在這裡面
from flask_mail import Mail, Message
reload(sys)
sys.setdefaultencoding(\'utf-8\')
app = Flask(__name__)
# 配置郵件:伺服器/端口/安全套接字層/郵箱名/授權碼/預設的發送人
app.config[\'MAIL_SERVER\'] = "smtp.qq.com"
app.config[\'MAIL_PORT\'] = 465
app.config[\'MAIL_USE_SSL\'] = True
app.config[\'MAIL_USERNAME\'] = "[email protected]"
# 這裡的密碼是你在郵箱中的授權碼
app.config[\'MAIL_PASSWORD\'] = "qyzlojxdaledcmhbjbb"
# 顯示發送人的名字
app.config[\'MAIL_DEFAULT_SENDER\'] = \'123456<[email protected]>\'
mail = Mail(app)
@app.route(\'/\')
def index():
return \'<a href="{}">發送郵件<a/>\'.format(url_for(\'send_mail\'))
@app.route(\'/send_mail\')
def send_mail():
message = Message(\'我是郵件的主題\', [\'[email protected]\'])
# message.body = \'我是内容\'
message.html = \'<h1>我也是内容<h1/>\'
mail.send(message)
return \'郵件發送中......\'
if __name__ == \'__main__\':
app.run(debug=True)
2.多線程的發送
# encoding: utf-8
import sys
from flask import Flask, url_for
# Mail可以看作是郵件的用戶端
# Message代表目前要發出的資訊,主題/内容/接收人都封裝在這裡面
from flask_mail import Mail, Message
from threading import Thread
reload(sys)
sys.setdefaultencoding(\'utf-8\')
app = Flask(__name__)
# 配置郵件:伺服器/端口/安全套接字層/郵箱名/授權碼/預設的發送人
app.config[\'MAIL_SERVER\'] = "smtp.qq.com"
app.config[\'MAIL_PORT\'] = 465
app.config[\'MAIL_USE_SSL\'] = True
app.config[\'MAIL_USERNAME\'] = "[email protected]"
# 這裡的密碼是你在郵箱中的授權碼
app.config[\'MAIL_PASSWORD\'] = "qyzlojxdaledcmhbjbb"
# 顯示發送人的名字
app.config[\'MAIL_DEFAULT_SENDER\'] = \'123456<[email protected]>\'
mail = Mail(app)
def send_mail_thread(message):
# 在新的線程中要,手動開啟應用上下文,不然會報錯
# RuntimeError: Working outside of application context.
with app.app_context():
mail.send(message)
@app.route(\'/\')
def index():
return \'<a href="{}">發送郵件<a/>\'.format(url_for(\'send_mail\'))
@app.route(\'/send_mail\')
def send_mail():
message = Message(\'我是郵件的主題\', [\'[email protected]\'])
# message.body = \'我是内容\'
message.html = \'<h1>我是内容<h1/>\'
thread = Thread(target=send_mail_thread, args=(message,))
thread.start()
return \'郵件發送中......\'
if __name__ == \'__main__\':
app.run(debug=True)
flask發送電子郵件