flask发送电子邮件
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)
版权声明:本文为songyanxin原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。