在Python中使用Flask发送HTML电子邮件 [英] Send html email using flask in Python

查看:501
本文介绍了在Python中使用Flask发送HTML电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Python和Flask将HTML网页作为邮件正文发送。我尝试使用MIME模块,但是以某种方式无法发送邮件。如果有人对此有任何专业知识,可以请帮助我。

I want to send HTML webpage as a mail body using Python and Flask. I tried using MIME module, but somehow I am not being able to send mail. If anyone has any expertise on this, can you please help me.

如果您还可以提供一些代码,那就太好了。

It would be great if you could provide some code as well.

推荐答案

使用flask-mail是一个很好的工具,请尝试尝试使用代码来渲染模板以将HTML呈现为邮件正文。

use flask-mail is a good tool and try is code I use to render the template to render Html as the body of my mail.

from flask_mail import Message
from flask import render_template
MAIL_USERNAME = os.environ.get('MAIL_USERNAME')
MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD'
    
def send_mail_flask(to,subject,template,**kwargs):
    msg = Message(subject=subject,sender='email@ofTheSender.com', recipients=to)
    msg.body = render_template(template+'.txt', **kwargs)
    msg.html = render_template(template+'.html', **kwargs)
    mail.send(msg)

模板是您要发送的HTML的路径,还可以添加邮件的文本版本!

the template is the path to your HTML you need to send you can also add a text version of the mail!

您可能需要根据使用的SMTP服务添加更多环境变量。

you may need to add more environment variables according to the SMTP service you use.

这篇关于在Python中使用Flask发送HTML电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆