Django错误:电子邮件发送时使用HTML代码,而不是显示模板



嘿,伙计们,我正试图通过django发送一封带有html模板的电子邮件,我面临着这个问题,因为电子邮件显示的是html代码而不是模板。我对下一步该做什么感到困惑。有人能告诉我代码的问题吗。

我使用Office365设置了电子邮件。

@app.task(name="account_opening_email")
def account_opening_email(email):
""" Method to send account opening email
:argument
1) email
"""
try:
user        = Account.objects.get(email=email)
subject     = "Signup Successful"
html_msg    = render_to_string('accounts/Welcome email.html', context={"username": user.first_name})
plain_msg   = strip_tags(html_msg)
from_email  = settings.EMAIL_HOST_USER
to_email    = [user.email]
msg = EmailMultiAlternatives(subject=subject, body=plain_msg, from_email=from_email, to=to_email)
msg.attach_alternative(html_msg, "text/html")
msg.content_subtype = 'html'
msg.mixed_subtype = 'related'
try:
for i in range(1, 11):
img_path = settings.STATIC_ROOT + f'/images/image-{i}.png'
image_name = Path(img_path).name
with open(img_path, 'rb') as f:
image = MIMEImage(f.read())
msg.attach(image)
image.add_header('Content-ID', f"<{image_name}>")
except:
pass
msg.send()
logger.info("Email Send")
except:
logger.exception("Failed")

谢谢。

我建议您使用email.mime模块来创建消息对象。这是我经常用来创建MIME电子邮件对象的方法(我使用Google GMail API发送它们,但应该与任何其他对象一起使用,例如smtplib(:

from email.mime.text import MIMEText
def create_message(email):
"""
Builds an MIME email object.
Parameters:
email: email address to send to

Returns:
A MIME email object
"""
message_html = render_to_string('accounts/Welcome email.html', context={"username": user.first_name})
message = MIMEText(message_html, 'html')
message['to'] = email
message['from'] = settings.EMAIL_HOST_USER
message['subject'] = "Signup Successful"
return message

这些在我的收件箱中自动呈现为HTML(我使用gmail(,就像我收到的所有商业电子邮件一样。

最新更新