In this Django article i want to show you How to Send Email to Gmail Account, basically sending emails with Django is easy and straightforward. the most important thing is to have a local SMTP server or define the configuration of an external SMTP server.
Also you can check
1: How To Build News Application In Django
OK now first of all you need to create a new django project using this command. i have called the project MyProject
1 |
django-admin startproject ProjectName |
First of all you need to change directory to the created project and after that you need to create an App, i have called the app MyApp.
1 |
python manage.py startapp MyApp |
So now you need to add some configuration of SMTP server, open your settings.py file and add these configurations.
1 2 3 4 5 6 7 8 9 10 11 12 |
if not DEBUG: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST_USER = "Youremail@gmail.com" EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_PASSWORD = "Your Password" else: EMAIL_BACKEND = ( "django.core.mail.backends.console.EmailBackend" ) |
OK in the above code iam using GMAIL SMTP Server, but if you have your own you can change that. also iam telling to django that if my django project is not in debug mode, use the real SMTP Server, but if it is in debug mode you can use django backend console for email.
- EMAIL_BACKEND: This is the backend for the email
- EMAIL_HOST_USER: Username for the SMTP server
- EMAIL_HOST: The SMTP server host; the default is localhost
- EMAIL_PORT: The SMTP port; the default is 25
- EMAIL_HOST_PASSWORD: Password for the SMTP server
- EMAIL_USE_TLS: Whether to use a TLS secure connection
- EMAIL_PASSWORD: This is the password
After this you need to open django shell using this command .
1 |
python manage.py shell |
Now you need to import send_mail() method form django.core.mail.
1 |
form django.core.mail import send_mail |
After this write this code for sending email.
1 2 |
send_mail('django test mail', 'this is django test body', 'youremail@gmail.com', ['youremail@gmail.com'], fail_silently=False) |
The send_mail() function takes the subject, message, sender, and list of
recipients as required arguments. By setting the optional argument
fail_silently=False, we are telling it to raise an exception if the email
couldn’t be sent correctly. If the output you see is 1, then your email
was successfully sent.
Note: If you are sending emails by Gmail with the preceding
configuration, you might have to enable access for less secured apps, you can check this link for more information
https://support.google.com/accounts/answer/6010255?hl=en
also of you have two step verification for your gmail account, you can not enable less secure apps in gmail.
After runing the code you these the are outputs for the console and also gmail.
Also you can watch the complete video for this article
Subscribe and Get Free Video Courses & Articles in your Email