我正在尝试通过django发送电子邮件。这是我的order.html文件:
<body>
<img src="{% static 'assets/img/logo/original.jpg' %}" alt="">
{% for order in orders1 %}
<h1>Your order number is <strong>{{order}}</strong></h1>
{% endfor %}
</body>
这是我的order.txt文件:
{% for order in orders1 %}
Your order number is {{order}}
{% endfor %}
这是我的views.py:
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context
def email(request):
orders1=Order.objects.filter(id=20)
d = { 'orders': Order.objects.filter(id=20) }
subject, from_email, to = 'hello', settings.EMAIL_HOST_USER, 'vatsalj2001@gmail.com'
text_content = get_template('emails/order.txt').render(d)
html_content = get_template('emails/order.html').render(d)
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
return render(request,'emails/order.html',{'orders1':orders1})
令人担忧的是,正在发送的电子邮件只包含主题(‘hello’),并且在电子邮件正文中显示了一个图标(带十字),而不是我想要的图像,也没有显示我在模板中设置的文本。另外,有什么需要和要求有一个文本和html文件的电子邮件?
发布于 2020-09-01 05:45:21
对你的程序(UnTested)做了一些修改,这应该可以工作
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string , get_template
from django.template import Context
def email(request):
orders1=Order.objects.filter(id=20)
subject, from_email, to = 'hello', settings.EMAIL_HOST_USER, 'vatsalj2001@gmail.com'
text_content = render_to_string('emails/order.txt',{'orders1': Order.objects.filter(id=20),})
html_content = render_to_string('emails/order.html', {'orders1': Order.objects.filter(id=20),})
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
return render(request,'emails/order.html',{'orders1':orders1})
匹配您传递给文本和html文件的密钥orders
,而访问orders1
时,您传递的是‘orders
要在电子邮件中渲染图像,您必须将图像托管在某个公共URL中,并将该路径添加到电子邮件正文中
编辑
文本内容可以直接分配,不需要从文件中加载,也不需要以其他方式添加文本内容,而无需创建单独的文件
from django.utils.html import strip_tags
text_content = strip_tags(html_content)
https://stackoverflow.com/questions/63681867
复制