Categories
Python Answers

How to create email templates with Python Django?

Spread the love

To create email templates with Python Django, we use the EmailMultiAlternatives class.

For instance, we write

from django.core.mail import EmailMultiAlternatives

subject, from_email, to = 'hello', 'from@example.com', 'to@example.com'
text_content = 'This is an important message.'
html_content = '<p>This is an <strong>important</strong> message.</p>'
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()

to create a EmailMultiAlternatives instance with the subject, text_content, from_email, and to.

And then we add HTML content by calling attach_alternative with html_content and 'text/html'.

Finally, we call send to send the email.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *