码迷,mamicode.com
首页 > 其他好文 > 详细

flask发送电子邮件

时间:2019-06-21 12:53:04      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:targe   封装   word   contex   url   邮件   err   form   work   

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] = "123456@qq.com"
# 这里的密码是你在邮箱中的授权码
app.config[MAIL_PASSWORD] = "qyzlojxdaledcmhbjbb"
# 显示发送人的名字
app.config[MAIL_DEFAULT_SENDER] = ‘123456<123456@qq.com>

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(我是邮件的主题, [‘123456@163.com])
    # 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] = "123456@qq.com"
# 这里的密码是你在邮箱中的授权码
app.config[MAIL_PASSWORD] = "qyzlojxdaledcmhbjbb"
# 显示发送人的名字
app.config[MAIL_DEFAULT_SENDER] = ‘123456<123456@qq.com>

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(我是邮件的主题, [‘123456@163.com])
    # 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发送电子邮件

标签:targe   封装   word   contex   url   邮件   err   form   work   

原文地址:https://www.cnblogs.com/songyanxin/p/11063606.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!