Django Email Sending

Django can send an email with its built-in library django.core.mail. You will require an SMTP account from your hosting provide or you may use Gmail. In this tutorial, we are going to use a gmail account. For this, you simply need to visit Gmail Account Settings and allow less secure app.

Django Email Setup

Django Mail Setup

Add the following attributes under

settings.py

    EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
    EMAIL_HOST = "smtp.gmail.com"
    EMAIL_PORT = 587
    EMAIL_HOST_USER = 'your_email@gmail.com' 
    EMAIL_HOST_PASSWORD = 'your_password'
    EMAIL_USE_TLS = True
                                

Now import the necessary packages and use the send_mail function as below:

from django.core.mail import send_mail

views.py

    from django.http import HttpResponse  
    from django.core.mail import send_mail
    from django.conf import settings
       
    def my_mail(request):  
        subject = "Greetings from Programink"  
        msg     = "Learn Django at Programink.com"  
        to      = "hello@programink.com"  
        res     = send_mail(subject, msg, settings.EMAIL_HOST_USER, [to])  
        if(res == 1):  
            msg = "Mail Sent Successfully."  
        else:  
            msg = "Mail Sending Failed."  
        return HttpResponse(msg)