未呈现Flask HTML电子邮件



我有一个flask应用程序,我想在那里发送一封电子邮件,以及从表单中提取的一些数据。一切都很好,但问题是,当收到电子邮件时,HTML代码没有呈现,它只显示原始代码。以下是我到目前为止所做的

if google_response['success']: #this line is used for a ReCaptcha response
msg = Message('Thank you for contacting me', sender='(my email address is put here as a string)', recipients=[request.form['email']])
name = request.form['name']
msg.body = render_template('email.html', name=name)
mail.send(msg)
return render_template('index.html')
else:
return render_template('index.html')

什么,我做错了吗?

我认为这与创建电子邮件的方式有关。你应该使用Multipart Email来实现这一点。我的猜测是,你使用HTML作为电子邮件的文本,而不是实际将其附加到电子邮件中。

由于您还没有向我们提供任何这些代码,我将给您一个如何生成包含HTML格式的电子邮件的示例。

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
to_address = ''
from_address = ''
msg = MIMEMultipart('alternative')
msg['Subject'] = ''
msg['From'] = from_address
msg['To'] = to_address
text = ''
html = 'your HTML code goes here'
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
msg.attach(part1)
msg.attach(part2)
mail = smtplib.SMTP('smtp.gmail.com', 587)
mail.ehlo()
mail.starttls()
mail.login('', '')
mail.sendmail(to_address, from_address, msg.as_string())
mail.quit()

最新更新