DEV Community

Lakshyaraj Dash
Lakshyaraj Dash

Posted on

How to send emails using python django ?

Many of us know the most common way of sending emails in the django using the django.core.mail. But have you all ever tried the most common way of sending emails throughout python ?

It's done by using the smtplib.

Demo code:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from decouple import config

def sendMail(fromEmail, toEmail, subject, message):
    msg = MIMEMultipart()
    msg.set_unixfrom("") # Put your name or any string
    msg["From"] = fromEmail
    msg["To"] = toEmail
    msg["Subject"] = subject
    msg.attach(MIMEText(message))
    mailserver = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    mailserver.ehlo()
    mailserver.login(config("EMAIL_ADDRESS"), config("EMAIL_PASSWORD"))
    mailserver.sendmail(fromEmail, toEmail, msg.as_string())
    mailserver.quit()
Enter fullscreen mode Exit fullscreen mode

Requirements of the above code is only the python-decouple module to read the local environment vars from .env files.

Documentation for python decouple: https://github.com/henriquebastos/python-decouple/
Documentation for smtplib: https://docs.python.org/3/library/smtplib.html

Top comments (0)