from flask import Flask,render_template
from flask_mail import Mail, Message
from common import email_config
import os
# 获取环境变量 某些时候不需要发送
env = os.environ.get('dev', 'dev')
mail = Mail()
app = Flask(__name__)
app.config.from_object(email_config)
mail.init_app(app)
@app.route('/email_send_charactor/')
def email_send_charactor():
message = Message(subject='hello flask-mail',recipients=['2528585013@qq.com'],body='flask-mail测试代码')
try:
mail.send(message)
return '发送成功,请注意查收~'
except Exception as e:
print(e)
return '发送失败'
#发送一个html
@app.route('/email_send_html/')
def email_send_html():
message = Message(subject='hello flask-mail',recipients=['2528585013@qq.com'])
try:
#发送渲染一个模板
message.html = render_template('email_temp.html')
mail.send(message)
return '发送成功,请注意查收~'
except Exception as e:
print(e)
return '发送失败'
#发送附带附件的邮件
@app.route('/email_send_attach/')
def email_send_attach():
message = Message(subject='hello flask-mail',recipients=['2528585013@qq.com'],body='我是一个附件邮件')
try:
# message.attach邮件附件添加
# 方法attach(self,
# filename=None,
# content_type=None,
# data=None,
# disposition=None,
# headers=None):
with open('xxxx','rb') as fp:
message.attach("test.jpg", "image/jpg", fp.read())
mail.send(message)
return '发送成功,请注意查收~'
except Exception as e:
print(e)
return '发送失败'
if __name__ == '__main__':
app.run(debug=True)
原文地址:https://blog.csdn.net/qq_42817166/article/details/112849264
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。