DJANGO: How to Send Text and HTML Emails with Dynamic data in Python

DJANGO: How to Send Text and HTML Emails with Dynamic data in Python

DJANGO: How to Send Text and HTML Emails with Dynamic data in Python

In this Python tutorial, I will let you know how to send emails to user with template data in Django .

Sending emails to user via applications are very common and great feature to enhances the User Experience. For example, you have to send welcome email sometimes when user sign up on your website, forgot password emails etc.

When you will not define the format of mail content then all the content will be treated as simple text.

Email Configuration in Django

In this example, I will use my Gmail account credential as SMTP server. You can change your settings in settings.py file of the project.

...
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_PASSWORD='******'
EMAIL_HOST_USER='myaccount@gmail.com'
EMAIL_PORT = 587
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER

Never add your password or any confidential credentials to any file that you commit to version control, it should be placed inside the environment settings.

You can also configure the SMTP SSL connection using django-smtp-ssl package.

Run following command to install SMTP SSL email backend for Django :

pip install django-smtp-ssl

Change your setting in following way :

EMAIL_BACKEND = 'django_smtp_ssl.SSLEmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'myaccount@gmail.com'
EMAIL_HOST_PASSWORD = '******'
EMAIL_PORT = '465'
Configure the templates directory

In order to use the html template, I need to configure the templates directory inside the setting.py file.

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [os.path.join(BASE_DIR, 'templates')],
...
]

Now create a directory "templates" on root level of application and then create a html file "mail.html" inside the directory for email templates.

templates/mail.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Sending emails to user in Python</title>
  </head>
  <body>
    Hello {{user}},

    <p>Welcome to the world of programming</p>

    <p>Thanks,<br />ExpertPHP</p>
  </body>
</html>
views.py

from django.template import Context
from django.template.loader import render_to_string, get_template
from django.core.mail import EmailMessage


def sendmail(request):
	ctx = {
        'user': "Ajay"
    }
    message = get_template('mail.html').render(ctx)
    msg = EmailMessage(
        'Subject',
        message,
        'from@example.com',
        ['to@example.com'],
    )
    msg.content_subtype = "html"  # Main content is now text/html
    msg.send()
    print("Mail successfully sent")

Phone: (+91) 8800417876
Noida, 201301
Attention Required! | Cloudflare

Sorry, you have been blocked

You are unable to access ressim.net

Why have I been blocked?

This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.

What can I do to resolve this?

You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page.