Sending Email with Python and Django

To obtain your SMTP credentials you can create a free outbound account with CloudMailin.

Sending mail with Django

Django includes the django.core.mail module to make sending email simple (django docs).

from django.core.mail import send_mail

send_mail(
    'Subject here',
    'Here is the message.',
    'from@example.com',
    ['to@example.net'],
    fail_silently=False,
)

Mail is sent using the following settings:

# settings.py
EMAIL_HOST = 'host from account page'
EMAIL_HOST_USER = 'username from account page'
EMAIL_HOST_PASSWORD= 'password from account page'
EMAIL_PORT = 587
EMAIL_USE_TLS = True

Sending mail with Plain Python

The django.core.mail module is really just a useful wrapper around the smtplib module. We can use the core smtplib to send email using STARTTLS and login authentication like the following:

import smtplib, ssl

hostname = "host from account page"
username = "username from account page"
password = "password from account page"

message = """\
Subject: Test from Python
To: to@example.net
From: from@example.com

This message is sent from Python."""

server = smtplib.SMTP(hostname, 587)
server.ehlo() # Can be omitted
server.starttls(context=ssl.create_default_context()) # Secure the connection
server.login(username, password)
server.sendmail("from@example.com", "to@example.net", message)
server.quit

It's imporant to note that CloudMailin will only allow auth after the starttls command has been passed.

Summary

We should now have received a message in our inbox. Using CloudMailin we can also track the status of each of our emails and see the delivery details. Any tags you've added as a x-cloudmta-tags header can be used to filter the email messages and search.

If you need any SMTP credentials you can create an account for free and get your SMTP credentials on the outbound account page.

Make sure you changed the from address to match your verified domain and set a recipient

Outbound Dashboard Showing Message

The SMTP transaction will reply with the message-id of the message to use for bounce tracking if required.

250 Thanks! Queued as: f78b876d-dd97-4e10-9a61-067f98044cc7

Of course if there are any questions feel free to contact us and we'll do our best to help you get setup sending email.