Search code examples
pythondjangodjango-modelsdjango-viewsdjango-mailer

How to send HTML in email using Django?


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 ?


Solution

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