Python html电子邮件模板的Django呈现为字符串不工作

Python html电子邮件模板的Django呈现为字符串不工作,python,django,web,Python,Django,Web,我试图发送一封风格化的电子邮件给一个新客户,一旦他们提交了我的网站上的付款。我在某个地方读了一些文章,尝试了我使用的render-to-string方法。电子邮件触发正确,唯一的问题是它似乎没有使用电子邮件模板。这是一封基本的纯文本电子邮件 请看下面我的代码。任何关于如何使这项工作的帮助都将是巨大的 Django视图代码 notice_html = render_to_string('MY_app/email-template.html') subject = 'Your New Design

我试图发送一封风格化的电子邮件给一个新客户,一旦他们提交了我的网站上的付款。我在某个地方读了一些文章,尝试了我使用的render-to-string方法。电子邮件触发正确,唯一的问题是它似乎没有使用电子邮件模板。这是一封基本的纯文本电子邮件

请看下面我的代码。任何关于如何使这项工作的帮助都将是巨大的

Django视图代码

notice_html = render_to_string('MY_app/email-template.html')
subject = 'Your New Design Confirmation'
from_email = settings.EMAIL_HOST_USER
recipient_list = [request.POST.get('email')]
message = "A curated message based on the design the customer purchased."
send_mail(
    subject=subject, message=message,
    recipient_list=recipient_list,
    from_email=from_email, fail_silently=False
)
模板中的Html

<div class="email-message">
    {{ send_mail.message }}
</div>

{{send_mail.message}}

您必须将
html\u消息
提供给(),并将消息作为上下文添加到模板中以使用消息:



message = "A curated message based on the design the customer purchased."
# Add the message to render_to_string to use it in template
notice_html = render_to_string(
    'MY_app/email-template.html',
    { "message": message }
)
...

send_mail(
    subject=subject, 
    message=message, 
    recipient_list=recipient_list, 
    from_email=from_email, 
    fail_silently=False,
    html_message=notice_html ⬅️
)

我尝试了emailmultialternatives,但没有成功,因为我不确定应该包含哪些上下文。我会试试这个,然后回来汇报。谢谢你的帮助。所以解决方案成功了,但是我在电子邮件模板中的CSS样式没有显示?@Vandle0,在电子邮件模板中,你必须使用内部或内联样式。您是否尝试使用:

{{{message}}

或内部
.email message{color:red;}
。我认为可能是因为我的站点仍在本地计算机上,而不是在生产服务器上。我刚刚开始使用内联样式,它很管用。谢谢你的提示@Vandle0,您仍然可以使用文件的图像。注意,您必须使用完整路径:
http://www.example.com/static/img/logo.png
。当然,你也可以附加一个文件:
email.attach\u file('attachment.pdf')
<div class="email-message">
    {{ message }}
</div>
from django.core.mail import EmailMultiAlternatives, get_connection

# By default fail_silently is already False
connection = get_connection(fail_silently=False)

message = "A curated message based on the design the customer purchased."
notice_html = render_to_string('MY_app/email-template.html', { "message": message })
subject = 'Your New Design Confirmation'

email = EmailMultiAlternatives(
    subject=subject,
    body=message,
    from_email=from_email
    to=recipient_list,
    connection=connection
)
email.attach_alternative(notice_html, "text/html")
email.send()