VATSAL JAIN
VATSAL JAIN

Reputation: 581

Having problem in sending email through django using EmailMultiAltenatives

I am trying to send emails through django. This is my order.html file:

<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>

This is my order.txt file:

{% for order in orders1 %}
Your order number is {{order}}
{% endfor %}

And this is my 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, '[email protected]'
    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})

The concern is that the email which is being sent only contains the subject('hello') and in the email body there shows an icon(with a cross) instead of image that I want and also no text shows up which I set in template. Also what is the need and requirements of having a text and html file for email?

Upvotes: 0

Views: 202

Answers (1)

Anurag
Anurag

Reputation: 3114

Made some changes to your program (UnTested), this should work

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, '[email protected]'
    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})

Match the key orders which you are passing to text and html files, you are passing 'orders', whereas accessing orders1

For rendering image in the email you have to host the image at some public URL and add that path in the email body

EDIT

Text content can be directly assigned, no need to load it from a file Or another way to add text content without creating separate file

from django.utils.html import strip_tags

text_content = strip_tags(html_content)

Upvotes: 1

Related Questions