Sending Emails from Python Django using your gmail account

Normally applications need to send the verification code or welcome messages to the registering user for their application using emails.

Sending email is not hard in if we are developing the backend of the application using Python or Python framework like Django.

As the first step we need to configure our gmail account to allow us to send email using code without login in to gmail and sending manually.

  • Login to your gmail account
  • Click on the profile icon shown in the top right corner of the browser window in gmail
  • Click on "Manage your Google Account" button like shown in the below image.

Screenshot 2022-06-25 at 10.40.37.png

  • Choose Security tab in the screen shown after the above step

Screenshot 2022-06-14 at 10.07.54.png

  • Scroll down to see the section "Signing in to Google" section
  • Enable two step verification there by giving your mobile number or some other method of verification.

Screenshot 2022-06-21 at 07.10.42.png

Screenshot 2022-06-21 at 07.11.14.png

  • Once clicked on Get Started button on the popup ti will ask you to login again.
  • Once the above step finished you can see a new item in the "Signing in to Google" section which will look like the below

image.png

  • Click on the App passwords in the above mentioned window which will open up another screen where you have to select the custom app name and generate a password.

image.png

image.png

  • Once you give a name for your app the "GENERATE" button will be enabled click on it to generate the password and copy the password. The password shown here is only showing one time there for carefully copy it and past it in a place where you can access later.

We have finished the configuration of gmail now. We can use the gmail as the sender email in our Django code.

Goto the Django settings file and make the configuration settings like below

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587

EMAIL_HOST_USER = 'your_username@gmail.com' # replace your_username
EMAIL_HOST_PASSWORD = 'xxxxxxxxxxxxxxxx' # use password generated above

In your model file you need to import the EmailMultiAlternatives from Django core module then you can send the email using the below lines of code.

from django.core.mail import EmailMultiAlternatives    

message = EmailMultiAlternatives(
       subject = subject,
       body = body,
       from_email = settings.EMAIL_HOST_USER,
       to = [email,] #more email address can be added
)

message.mixed_subtype = 'related'
message.attach_alternative(body, "text/html")
message.send()