How to Send Emails and Attachments using Django
In this post, we’ll learn how to set an email in our Django project. Django makes it convenient to send emails and provides with various methods for our needs.
Table of Contents
- Set-up Email SMTP
- Sending a simple email
- Sending email using templates
- Sending email using attachments
- Sending Bulk Email
- Conculsion
Set-up Email SMTP
Before we begin we must set up email setting in `settings.py` file.
EMAIL_HOST='smtp.sendgrid.net' EMAIL_HOST_USER='username' EMAIL_HOST_PASSWORD='password' EMAIL_PORT = 587 EMAIL_USE_TLS = True
In settings.py
file i have used EMAIL_HOST='smtp.sendgrid.net'
you may use any other smtp host such as google smtp or any other.
We have created a app called test_email
and we are imported views from app and also don’t forget to include test_email
in installed apps
.
In test_email/urls.py
from django.urls import path, include from test_email.views import ( simple_email, email_with_template, email_with_attachment, email_with_custom_attachment_file_name, bulk_email, ) from django.conf import settings from django.conf.urls.static import static app_name='test_email' urlpatterns = [ path('simple_email',simple_email, name='simple_email'), path('email_with_template',email_with_template, name='email_with_template'), path('email_with_attachment',email_with_attachment, name='email_with_attachment'), path( 'email_with_custom_attachment_file_name', email_with_custom_attachment_file_name, name='email_with_custom_attachment_file_name' ), path('bulk_email',bulk_email, name='bulk_email'), ]
Sending a simple email
We’ll start by sending simple email for we’ll import send_mail
from module django.core.mail
.
Django provides convenient send_mail()
function which takes below arguments.
Syntax
send_mail(subject, message, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None, html_message=None)
send_mail arguments
fail_silently : options : True/False
When set to True the error are displayed in the view.
When set to False the error occured are ignored.
auth_user : optional field which recieved authenticated username for email.
auth_password : optional field which recieved authenticated password for email.
connection : optional field which recieved default settings.EMAIL_BACKEND or we can specify other EMAIL_BACKEND in settings.py file.
html_message : optional arguments which received message html content.
In test_email/views.py
import os from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.conf import settings from django.template.loader import get_template,render_to_string # django email module from django.core.mail import send_mail,EmailMessage,send_mass_mail def simple_email(request,*args,**kwargs): subject = 'This is email subject' msg = 'This is the message of email' from_email = 'fromemail@example.com' to_email = ['toemail1@example.com','toemail2@example.com'] # can send email to multiple recipients email_res = send_mail(subject,msg,from_email,to_email,fail_silently=False,) return HttpResponse(email_res)
email_res will return 1 if email is successfully sent.
Sending email using templates
Django provides django.template.loader
module which provides us functions to send email using template.
Therender_to_string()
is method which takes template_name, context as arguments this function return to template contents to html.
Syntax:
render_to_string(template_name, context=None, request=None, using=None)
render_to_string() arguments.
- template_name : Takes the path to html template.
- context : It is the data to be passed to html template.
- request : It takes request object.
- using : It is the templating engine.
Creating Template
We are creating template in path="test_email/template/test_email/simple_email.html"
.
<h2>Welcome to Company Name</h2> <p><strong>Dear {{first_name}} {{last_name}},</strong></p> You have successfully registered by user name <strong>"{{username}}"</strong>
In test_email/views.py
def email_with_template(request,*args,**kwargs): subject = 'This is email subject' ctx = { 'username' : 'Alen1234', 'first_name':'Alen', 'last_name':'Jake', } msg = render_to_string('test_email/simple_email.html',ctx) from_email = 'fromemail@example.com' to_email = ['toemail@example.com'] # can send email to multiple recipients email_res = send_mail(subject, '', from_email, to_email, fail_silently=False, html_message=msg) return HttpResponse(email_res)
Sending email using attachments
django.core.mail
provides EmailMessage
is a class through which we can send attachments through email.
In test_email/views.py.
def email_with_attachment(request,*args,**kwargs): file_path = os.path.abspath('media/bg-2.jpg') subject = 'This is email subject' ctx = { 'username' : 'Alen1234', 'first_name':'Alen', 'last_name':'Jake', } msg = render_to_string('test_email/simple_email.html',ctx) from_email = 'fromemail@example.com' to_email = ['toemail@example.com'] mail = EmailMessage( subject, msg, from_email, to_email, ) mail.content_subtype='html' mail.attach_file(file_path) email_res = mail.send() return HttpResponse(email_res)
Sending Bulk Email
Django django.core.mail
provides send_mass_mail()
function which under the hood it calls the class EmailMessage
. But send_mass_mail()
keep the connection open whereas send_mail
closes the connection once after execution.
Syntax:
send_mass_mail(datatuple, fail_silently=False, auth_user=None, auth_password=None, connection=None)
send_mass_mail()
arguments.
datatuple : takes multiple tuples which include subject, from_email, to_email, msg.
In test_email/views.py.
def bulk_email(request,*args,**kwargs): ctx_list = [ { 'username' : 'Alen1234', 'first_name':'Alen', 'last_name':'Jake', 'email':'toemail@example.com', 'subject':'email subject', 'msg':'This is the email msg' }, { 'username' : 'Tim34', 'first_name':'TIm', 'last_name':'Crook', 'email':'toemail@example.com', 'subject':'email subject', 'msg':'This is the email msg' }, ] from_email='fromemail@example.com' email_tuple = tuple() for i in ctx_list: email_tuple=email_tuple+(( i['subject'], i['msg'], from_email, [i['email']]),) email_res = send_mass_mail((email_tuple), fail_silently=False) return HttpResponse(email_res)
Note
Visit Official Django Website to know more about sending emails.
Conculsion
We have come to the end of this post. Hope we have answered your queries regarding How to Send Emails and Attachments using Django.
Help us improve this post by commenting. If you like then don’t forget to share.




