DEV Community

Cover image for Sending Emails in Django
Madhuban Khatri
Madhuban Khatri

Posted on • Edited on

4 1

Sending Emails in Django

Configuration for Sending Emails in Django:-

Watch my video on YouTube

settings in Your Gmail Account

Alt Text

  • Open your email account in Browser
  • go to 'Manage your google account'
  • go to 'Security' tab in left side bar
  • Turn ON the Toggle Button in 'Less Secure App Access' option in Security tab.

settings.py

Add Some line of Code in this file.

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

EMAIL_HOST = 'smtp.gmail.com'

EMAIL_USE_TLS =True

EMAIL_PORT = 587

EMAIL_HOST_USER = 'your email id'

EMAIL_HOST_PASSWORD = 'password'
Enter fullscreen mode Exit fullscreen mode

project/urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('main.urls')),
]
Enter fullscreen mode Exit fullscreen mode

app/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('send_mail/', views.sendMail, name='send_mail')
]
Enter fullscreen mode Exit fullscreen mode

views.py

from django.shortcuts import render, redirect
from django.conf import settings
from django.core.mail import send_mail
from django.contrib import messages
# Create your views here.
def home(request):
    return render(request, 'home_page.html')



def sendMail(request):
    if request.method == 'POST':
        sender = settings.EMAIL_HOST_USER
        receiver = request.POST['receiver']
        subject = request.POST['sub']
        content = request.POST['content']

        mail = send_mail(subject, content, sender, [receiver], fail_silently=False)
        if mail:
            messages.success(request, 'Email has been sent.')
            return redirect('home')
        else:
            return HttpResponse('message not sent')
    else:
        return redirect('home')
Enter fullscreen mode Exit fullscreen mode

templates/home.html

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">

    <title>Sending Email in Django</title>
  </head>
  <body class="bg-dark text-light">
    <div class="container my-3" style="width: 500px;">

      <h2 class="alert alert-success">Sending Email in Django</h2>
      <hr>
      {% if messages %}
      {% for message in messages %}
      <div class="alert alert-dark alert-dismissible fade show my-4" role="alert">
      {{message}}
      <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
      {% endfor %}
      {% endif %}


    <form action="{% url 'send_mail' %}" method="post">
      {% csrf_token %}
      <div class="mb-3">
        <label for="exampleInputEmail1" class="form-label"><b>To</label>
        <input type="email" class="form-control" name="receiver" id="exampleInputEmail1" aria-describedby="emailHelp">
      </div>
      <div class="mb-3">
        <label for="subject" class="form-label"><b>Subject</label>
        <input type="text" class="form-control" name="sub" id="subject">
      </div>
      <div class="mb-3">
        <label for="content" class="form-label">Body</label>
        <textarea class="form-control" name="content" style="height: 250px;"></textarea>

      </div>

      <button type="submit" class="btn btn-primary">Send</button>
    </form>


    </div>



    <!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>


  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (2)

Collapse
 
segestic profile image
segestic

Nice work. Keep it up!

Collapse
 
cpoonam47 profile image
cpoonam47

Wonderfull, Nice Work , I want to add my project file

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay