March 20th, 2012

Django NTLM SMTP Auth

Tutorial for: Django


Are you trying to use a Corporate SMTP Server with Django? Does this SMTP Server only support NTLM Domain authentication? This tutorial is definitely for you!

I needed to develop an internal reporting application at work, and I wanted to build it using Python, rather than .NET or what have you. Python is great for report processing, and Django makes it a cinch to build nice templates to Email out.

When looking into how to interface Django with our corporate SMTP Server, which only accepts NTLM authentication, I stumbled upon python-ntlm. It didn't support SMTP sending natively, but supports NTLM authentication. There is a patch involved in order to make python-ntlm support SMTP Auth correctly, you can find the patch in issue 14. Here is the backend which you can add to your Django project to enable sending mail through an NTLM authenticated SMTP Host:

from django.core.mail.backends.smtp import EmailBackend
from ntlm.smtp import ntlm_authenticate
import smtplib
from django.core.mail.utils import DNS_NAME

class NTLMEmail(EmailBackend):
    def open(self):
        Ensures we have a connection to the email server. Returns whether or
        not a new connection was required (True or False).
        if self.connection:
            # Nothing to do if the connection is already open.
            return False
            # If local_hostname is not specified, socket.getfqdn() gets used.
            # For performance, we use the cached FQDN for local_hostname.
            self.connection = smtplib.SMTP(, self.port,
            if self.username and self.password:
                ntlm_authenticate(self.connection, self.username, self.password)
            return True
            if not self.fail_silently:

Save this into a somewhere in your project. The name of the python file doesn't actually matter, as long as you can easily reference it via your Next you need to add the new backend to your

EMAIL_BACKEND = 'reporting.backends.NTLMEmail'
EMAIL_HOST = '**Corporate SMTP server**'
EMAIL_HOST_USER = r"**NT DOMAIN**\**NT Username**"

There you have it, now Django can freely email reports or anything from your Django application. Enjoy!

About Me

My Photo
Names Kevin, hugely into UNIX technologies, not just Linux. I've dabbled with the demons, played with the Sun, and now with the Penguins.

Kevin Veroneau Consulting Services
Do you require the services of a Django contractor? Do you need both a website and hosting services? Perhaps I can help.

This Month

If you like what you read, please consider donating to help with hosting costs, and to fund future books to review.

Python Powered | © 2012-2019 Kevin Veroneau