Django Gmail – How To Send Email In Django

Although Python provides how to send email in Django interface via thesmtplibmodule,but Django provides a couple of light wrappers over it. These wrappers are provided to make sending email extra quick, to help test email sending during development, and to provide support for platforms that can’t use SMTP.

If you are not familar with django project you can reffer to this project to start a django project

Before we continue, let me explain what we are to cover up in this tutorial.

ILLUSTARION OF HOW TO SEND EMAILS IN DJANGO

Thesubject,message,from_emailandrecipient_listparameters are required.

  • subject: A string.
  • message: A string.
  • from_email: A string. IfNone, Django will use the value of theDEFAULT_FROM_EMAILsetting.
  • recipient_list: A list of strings, each an email address. Each member ofrecipient_listwill see the other recipients in the “To:” field of the email message.
  • fail_silently: A boolean. When it’sFalse,send_mail()will raise ansmtplib.SMTPExceptionif an error occurs. See thesmtplibdocs for a list of possible exceptions, all of which are subclasses ofSMTPException.
  • auth_user: The optional username to use to authenticate to the SMTP server. If this isn’t provided, Django will use the value of theEMAIL_HOST_USERsetting.
  • auth_password: The optional password to use to authenticate to the SMTP server. If this isn’t provided, Django will use the value of theEMAIL_HOST_PASSWORDsetting.
  • connection: The optional email backend to use to send the mail. If unspecified, an instance of the default backend will be used. See the documentation onEmail backendsfor more details.
  • html_message: Ifhtml_messageis provided, the resulting email will be amultipart/alternativeemail withmessageas thetext/plaincontent type andhtml_messageas thetext/htmlcontent type.

The return value will be the number of successfully delivered messages (which can be0or1since it can only send one message).

Although you can refer to thedocumentationfor knowing more about sending emails in Django, but I have made this tuttorial very easy so that you can follow

There are many email providers but in this post I’d be writing only how to send mail in django using gmail

Illustration of Django emails using an example.

In this post we are going to send emails to any user that login to our site.The user will receive a message each time a login is made.

Illustration of how to send email to every signed in user in django

Consider a project named benchatronics having an app named django_emails. Refer tothisto create Django project and apps.

Before you continue go to gmail and navigate to security and enable two factor authentication.

Then create an app , after creating an app make sure to copy the password of the app you have created

Follow the image below to configure your own 2factor authentication and app password

2factor

Enable two factor auth, after enabling two factor you have to create app password by clicking on the app password below

app_password

This is how the password you will generate looks like

app password

I assumed that you have created a project with an app and you have configured your templates and static files if possible. now in your project saybenchatronics/django_emails/settings.py navigate to settings.py then configure and add this code to your settings.py and save.

Add these config anywhere in settings.py

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = #sender's email-id
EMAIL_HOST_PASSWORD = #password associated with above email-id

Now The Email_Host_User is the email you want use to be sending the email, this email work with distinct email providers.

While the Email_Host_Password is your Email password you have generated from the google 2 factor authentication

What do I mean; the configuration above is for gmail. If you are using Yahoo or others you have to google how to configure that

Now to use this in our application, let’s move tobenchatronics/django_emails/views.pyand add these lines at the top section as below.

#import these in your views.py
<strong>from</strong> django.conf <strong>import</strong> settings 

<strong>from</strong> django.core.mail <strong>import</strong> send_mail 

#create your views here
<strong>def</strong> <strong>contact</strong>(request):
    subject = 'welcome to benchatronics'
    message = 'Thanks for visiting, please visit again '

    email_from = 
    settings.EMAIL_HOST_USER 

    recipient_list = 
    

send_mail( subject, message, email_from, recipient_list ) context = {} return render(request,’home.html’,context)

Now remember to set up your urls in the app saybenchatronics/django_emails/urls.py

<strong>from</strong> django.urls <strong>import</strong> path
<strong>from</strong> . <strong>import</strong> views
#from .views import *


urlpatterns = [

    path('home/contact/',views.contact,name='home'),
]


You have to create a templates with the namehome.html

Remember to create your home html so that when ever a user visit it , the messge would be triggered

We have achieve the sending of email to every register user that visit or tour the site ; now we have to send message to every user that login in the site.

Django Email – Illustration of how to send confirmation login email to every user in django

To send email to a logged in user add this code on your sign in or login in form

to do that let’s edit the views.py. Add this code in your login views.


def <strong>login_user</strong>(request):
    
    <strong>if</strong> request.method == 'POST':
        username = request.POST['username']
        pass1 = request.POST['pass1']

        user = <strong>authenticate</strong>(username=username, password=pass1)
        context={'username':username,
                  'login_status':True,


       }
        response = <strong>redirect</strong>('/',context)
        response.<strong>set_cookie</strong>('username',username)
        response.<strong>set_cookie</strong>('login_status',True)

        <strong>if</strong> user is not  None:
            auth.<strong>login</strong>(request, user)
            subject = 'welcome to Benchatronics world'
            message = f'Hi {user.username},You have been logged <strong>in</strong> benchatronics.
            email_from = settings.EMAIL_HOST_USER
            recipient_list = [user.email, ]
            <strong>send_mail</strong>( subject, message, email_from, recipient_list )
            messages.<strong>info</strong>(request,'You have successfully logged <strong>in</strong>')
            <strong>return</strong> response


        <strong>else</strong>:
            messages.<strong>error</strong>(request,'bad credentials')
            <strong>return</strong> <strong>redirect</strong>('login')


    <strong>return</strong> <strong>render</strong>(request,"login.html",details)

Now head over tobenchatronics/django_emails/urls.pythen map the urls like example below.

<strong>from</strong> django.urls <strong>import</strong> path
<strong>from</strong> . <strong>import</strong> views

urlpatterns = [
    path('login',views.login_user, name='login'),
]

After adding save it; Remember you have to add your login.html for users to sign in

You have to create login form in other to complete this process.

python manage.py makemigrations

python manage.py migrate

python manage.py runserver

Now we are set to send automatic email ones a registered user access our website atlocalhost:127.0.0.0/home/contact

And each time a user logged in a welcome message would be sent to the user

2 thoughts on “Django Gmail – How To Send Email In Django

Leave a Reply

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