问题
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.
回答1:
Try using FlaskMail https://pythonhosted.org/flask-mail/
msg = Message(
recipients=[''],
sender='xx@zz.yy',
reply_to='aa@bb.cc',
subject=mail.subject
)
msg.html = mail.body
mail.send(msg)
here, mail is an imported file from "mails" directory,
and body is an HTML markup.
回答2:
use flask-mail is a good tool and try is code i use render template to render html as 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)
template is the path to your html you need to send you can also add a text version of the mail!
you may need to add more environement variables accoding to the SMTP service you use.
来源:https://stackoverflow.com/questions/42136418/send-html-email-using-flask-in-python