Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Django project to create a Comments System
Next article icon

Django, a high-levelPythonweb framework, provides built-in functionality to send emails effortlessly. Whether you're notifying users about account activations, sending password reset links, or dispatching newsletters, Django’s robust email handling system offers a straightforward way to manage email communication. This tutorial will guide you through the process of setting up and sending emails in Django, covering configuration, templates, and practical examples, ensuring that you can integrate email functionality into yourDjango applications with ease.

Django to send emails with SMTP

Consider a project named geeksforgeeks having an app named geeks. Referthis to create Django projects and apps. Now let's demonstrate this in geeksforgeeks project. In your "geeks" app'ssettings.py file, add the following code:

Python
EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend'EMAIL_HOST='smtp.gmail.com'EMAIL_USE_TLS=TrueEMAIL_PORT=587EMAIL_HOST_USER=#sender's email-idEMAIL_HOST_PASSWORD=#password associated with above email-id (not the regular password)

By default, Google does not allow third party apps to use mail services using our email address and actual password. So, we have to create an app password which will be only utilized by our Django mail application. In order to generate an app password for your google account, follow these steps:

Step 1

Sign in to your google account and click on Manage account.

image1
Step 1

Step 2

Enable two factor authentication by typing "2 step verification" on the search bar.

image2
Step 2

Step 3

After enabling 2FA, type "App passwords" on the search bar.

image3
Step 3

Step 4

Enter a project name and your unique password will be provided to use it in your project. Note that the password is only shown once, and it is valid until it is manually removed from the app passwords tab. Hence copy the password when it is shown and use it as EMAIL_HOST_PASSWORD in the Django settings.py file.

image4
Step 4 (i)
image5
Step 4 (ii)

The views.py file for this application contains the following code:

Python
fromdjango.shortcutsimportrenderfromdjango.httpimportHttpResponsefromdjango.core.mailimportsend_mailfromdjango.confimportsettingsdefsend_mail_page(request):context={}ifrequest.method=='POST':address=request.POST.get('address')subject=request.POST.get('subject')message=request.POST.get('message')ifaddressandsubjectandmessage:try:send_mail(subject,message,settings.EMAIL_HOST_USER,[address])context['result']='Email sent successfully'exceptExceptionase:context['result']=f'Error sending email:{e}'else:context['result']='All fields are required'returnrender(request,"index.html",context)

Now we will understand what exactly is happening. Here the send_mail() is an inbuilt Django function which takes 4 important arguments,

  • subject refers to the email subject.
  • message refers to the email message, the body of the email.
  • email_from refers to the sender's details. This takes the EMAIL_HOST_USER from settings.py file, where you added those lines of code earlier.
  • recipient_list is the list of recipients to whom the mail has to be sent.

The return value of this function is either 0 or 1 depending upon the number of messages sent.

Other optional arguments of the send_mail() function includes,

  • fail_silently: It is a boolean value used to raise an smtplib.SMTPException if an error occurs.
  • auth_user: The optional username to use to authenticate to the SMTP server. If this isn’t provided, Django will use the value of the EMAIL_HOST_USER setting.
  • auth_password: The optional password to use to authenticate to the SMTP server. If this isn’t provided, Django will use the value of the EMAIL_HOST_PASSWORD setting.
  • connection: The optional email backend used to send the mail. If unspecified, an instance of the default backend will be used.
  • html_message: It is used to send HTML pages in the mail body rather than sending plain text.

The index.html looks like:

HTML
{% load static %}<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><linkrel="stylesheet"href="{% static 'style.css' %}"/><title>Mail App</title></head><body><div><h1>Django Mail App</h1><formmethod="post">            {% csrf_token %}<labelfor="address">To:</label><inputid="address"type="email"name="address"/><labelfor="subject">Subject:</label><inputid="subject"name="subject"/><labelfor="message">Message:</label><br><textareaid="message"name="message"></textarea><inputtype="submit"></form><p>{{ result }}</p></div></body></html>

And the styles.css looks like:

CSS
h1{margin:10pxauto20pxauto;color:green;display:block;}input{width:300px;height:25px;display:block;margin-bottom:20px;}div{display:flex;flex-direction:column;align-items:center;}textarea{resize:none;width:302px;height:100px;margin-bottom:10px;}input[type="submit"]{width:150px;height:30px;background-color:green;color:white;border:none;margin:0auto;}

Add the following in urls.py:

Python
fromdjango.contribimportadminfromdjango.urlsimportpathfrommailsenderimportviewsurlpatterns=[path('admin/',admin.site.urls),path('',views.send_mail_page)]

Output

mail
Mail received

How to Send Beautiful Emails in Python (using Django)
Improve

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp