Dim
Dim

Reputation: 855

Django mail SMTPlib auth method problem

I am trying to send an email using Django and my client's smtp server. That server supports AUTH LOGIN commands only.

By default (as far as i can see using wireshark) django sends this bit:

250-AUTH=LOGIN CRAM-MD5 PLAIN

as part of the email message.

I have tracked that to /usr/lib/python/smtplib.py:569 where it chooses the authentication method (there's an option for AUTH_LOGIN which is what i want).

As far as i can see i can't set the auth method using vars in settings.py (http://docs.djangoproject.com/en/dev/topics/email/)

Does anyone know how i can tell Django to use auth_login instead of auth_cram_md5?

Upvotes: 0

Views: 2115

Answers (1)

lukasziegler
lukasziegler

Reputation: 416

I found a way to tell smtplib to use one specific authentication mechanism (credit goes to SMTP AUTH extension trouble with Python). The following line of code allows you to suggest authentication mechanisms to smtplib, ignoring other mechanisms offered by the server (e.g. CRAM-MD5 DIGEST-MD5):

server.esmtp_features['auth'] = 'LOGIN PLAIN'

Another common mistake found on many tutorials is that when using .starttls(), one needs to send the server.ehlo() twice, once before and once after the .starttls().

Here is the code which worked for me:

import smtplib

user = '<username>'
pwd = '<password>'

FROM = '[email protected]'
TO = ['[email protected]']
SUBJECT = 'Testing sending using gmail'
TEXT = 'Testing sending mail using gmail servers'

# Prepare actual message
message = """\From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

try:
    server = smtplib.SMTP("<SMTP-Server-URI>", 25)
    server.set_debuglevel(1) # optional, good for debugging
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.esmtp_features['auth'] = 'LOGIN PLAIN'
    server.login(user, pwd)
    server.sendmail(FROM, TO, message)
    server.close()
    print 'successfully sent the mail'
except:
    print 'failed to send mail'

This code was only tested with Python 2.7.9 (and not specifically with Django). Hope it helps some people.

Upvotes: 5

Related Questions