Send Emails Using Django

Django Send Email

In this article, we will learn to send emails using Django to users automatically via the Django mail library, an extension of the smtplib module of Python.

What is SMTP?

SMTP server stands for Simple Mail Transfer Protocol, which is a community protocol for electronic mail transmission. SMTP consists of a set of community guidelines that allows, softwares to transmit Mail over the internet. It is a program that sends mail to other users using email addresses.

SMTP server: is the application that sends/receives or relays outgoing mails from one client to another.

For Example, Google’s SMTP server address is smtp.gmail.com. Similarly, Apple’s SMT server is smtp.apple.com, etc.

How to Send Emails using Django?

Now that we know about the SMTP server is and how emails are generated, let us now make an app to send emails using Python Django.

1. Additions to Settings.py

In the settings.py file, we need to add the following email dictionary variable:

EMAILS = [
    {
        EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend',
        EMAIL_HOST = 'smtp.gmail.com',
        EMAIL_PORT = 8000,
        EMAIL_HOST_USER = '[email protected]',
        EMAIL_HOST_PASSWORD = 'xyz',
        EMAIL_USE_TLS = True,
        EMAIL_USE_SSL = False,
        }
]

Make sure you change the SMTP_HOST with the SMTP server from your provider. Also, change the email and the password with your credentials.

2. Difference between TLS and SSL

The functioning of both TLS and SSL is the same; they are used to encrypt data and information between servers/clients or systems. TLS (Transport Layer Security) is the successor protocol to SSL(Secure Sockets Layer).

TLS or SSL depends on the server you are using, in the case of Gmail, it is TLS.

In this article, I will be working with Gmail itself and hence will select TLS. You could use anything of the two based on your server.

Writing Code to send Emails

Now that we have our settings in place, let’s write the code to send emails.

1. Send emails individually using send_mail()

This section of the tutorial talks about the ways to send individual emails to your recepients. We’ll make this happen with the send_mail() function. The syntax for send_mail is:

send_mail(
    subject = 'This is Subject Message',
    message = 'This is email Message',
    from_email = 'Sender Email ID',
    recipient_list = 'Recipient's Email',
    fail_silently = False,
    html_messages = 'HTML messages',
)

In Views.py, add the code:

from django.core.mail import send_mail

send_mail(
    subject = 'Test Mail',
    message = 'Kindly Ignore',
    from_email = '[email protected]',
    recipient_list = ['[email protected]',],
    fail_silently = False,
)

2. Sending Multiple Emails using send_mass_mail()

In this section, we’ll go over the steps to send out bulk emails. We’ll use the send_mass_mail() method here. The syntax for send_mass_mails:

send_mass_mail(
    (datatuple),
    fail_silently = False,
)

Here the datatuple is the tuple containing the information about individual emails.

message1 = (subject, message, from_email, recipient_list)
message2 = (subject, message, from_email, recipient_list)
message3 = (subject, message, from_email, recipient_list)

send_mass_mail((message1,message2,message),fail_silently =False)

In views.py the code will look like:

from django.core.mail import send_mail

message1 = ('Subject Here', 'This is Message','[email protected]',['[email protected]','[email protected]'])
message2 = ('Subject Here', 'This is Message','[email protected]',['[email protected]','[email protected]'])


send_mass_mail(
    (message1,message2),
    fail_silently = False,
)

3. Send Emails using Django EmailMessage() Method

This method is used to send advanced mails, having features like BCC, CC, or attachments. This Django Method is handled by Email Backend.

The Email Backend class requires three steps:

  1. connection.open(): Ensures a long-term connection for sending mails.
  2. connection.close(): Stops the established connection
  3. send_message(): Sends the mails; if the connection was not already open, then it temporarily opens the connection to send the mail.

The placeholder syntax is :

email1 = EmailMessage(
    subject = 'This is subject',
    message = 'This is message',
    from_email = '[email protected]',
    to = ['[email protected]',],
    bcc = ['[email protected]'],
    cc = ['[email protected]'],
)

Therefore add the following code in view.py:

from django.core import mail
connection = mail.get.connection()

connection.open()

email = mail.EmailMessage(
    subject = 'Test Mail',
    message = 'Kindly Ignore',
    from_email = '[email protected]',
    to = ['[email protected]',],
    bcc = ['[email protected]'],
)

connection.send_messages(email)
connection.close()

File Attachment:

EmailMessages() method provides .attach_file(‘path to the file’) method to send attachments along with your email message. You can add the following code to attach the file:

email1.attach_file('home/Desktop/books.jpg')

Implementing the Code

Now that we’ve discussed the individual sections of code let’s put them all together and figure out how it works. Therefore add a sample script (combining all the codes from the above section) into your views.py:

from django.core.mail import send_mail

#Sending mails individualy
send_mail(
    subject = 'Test Send Mail #1',
    message = 'Kindly Ignore',
    from_email = '[email protected]',
    recipient_list = ['[email protected]',],
    fail_silently = False,
)

#Sending mass mails
message1 = ('Test Subject message1 #2', 'This is Message','[email protected]',['[email protected]','[email protected]'])
message2 = ('Test Subject message2 #2', 'This is Message','[email protected]',['[email protected]','[email protected]'])

send_mass_mail(
    (message1,message2),
    fail_silently = False,
)

#Sending mails using EmailMessage along with attachments
from django.core import mail
connection = mail.get.connection()

connection.open()
email = mail.EmailMessage(
    subject = 'Test Mail',
    message = 'Kindly Ignore',
    from_email = '[email protected]',
    to = ['[email protected]',],
    bcc = ['[email protected]'],
)
email.attach_file('home/Desktop/books.jpg')
connection.send_messages(email)
connection.close()

Note the first time you use Gmail to send emails; you might get an SMTP error due to the default security settings.

For that, go to manage your account in your sender gmail account

Manage You Account Edited
Manage You Account Edited

Then go to Security present on the top panel and turn on Less Secure access.

Less Secure Your Account
Less Secure Your Account

That’s it, now try and run your code! It will start sending emails. Run the server in the terminal:

python manage.py runserver

That’s it, All the emails are sent now! The emails will look like this:

Email
Email
Attachment Email
Attachment Email

Conclusion

That’s it, Coders! We can now successfully send emails from our Web Application using Django.

You can try implementing the above codes as practice. See you guys in the next article !! Keep practicing!!