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 file of the project.

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

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_PORT = '465'
Configure the templates directory

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

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

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

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

    <p>Thanks,<br />ExpertPHP</p>

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(
    msg.content_subtype = "html"  # Main content is now text/html
    print("Mail successfully sent")

Phone: (+91) 8800417876
Noida, 201301
sakarya escort sakarya escort sakarya escort sakarya escort serdivan escort izmir escort eporner
akyazı escort sakarya escort ferizli escort sakarya escort geyve escort sakarya escort hendek escort sakarya escort karasu escort sakarya escort sapanca escort serdivan escort webmaster forum ankara travesti