How to send HTML in email using Django?

6k views Asked by At

i am New in Django. i want to send html via Email using django. i am using following Code

  send_mail(
            'Email Title',
            'My Message',
            'webmaster@localhost', 
            [to mail],   
            fail_silently=False,
           ) 


  

This Code is Sending simple strings,not sending HTML. for example if i pass <h1>test</h1> in my message body then it will return same. i want to apply <h1> tag in 'test'. How to do that ?

2

There are 2 answers

1
Hritu Rathod On BEST ANSWER
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string

def send_emails(request):
    merge_data = {
        'greetings': "hello"
    }
    html_body = render_to_string("email-templates.html", merge_data)

    message = EmailMultiAlternatives(
       subject='Django HTML Email',
       body="mail testing",
       from_email='[email protected]',
       to=['[email protected]']
    )
    message.attach_alternative(html_body, "text/html")
    message.send(fail_silently=False)
0
Kishan Parmar On

you can do something like this this will work. but you have to pass that message in 'html_message'

from django.template import Template

send_mail(
        'Email Title',
        html_message = Template("<b>Hello</b>"),
        'webmaster@localhost', 
        [to mail],   
        fail_silently=False,

       )