DEV Community

Lakshyaraj Dash
Lakshyaraj Dash

Posted on

1

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

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

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

Okay