Skip to content

Instantly share code, notes, and snippets.

@vietvudanh
Forked from brianlittmann/EmailBackend.py
Created August 2, 2017 04:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vietvudanh/49c0d59d518a8d4770526dbb8ed478a9 to your computer and use it in GitHub Desktop.
Save vietvudanh/49c0d59d518a8d4770526dbb8ed478a9 to your computer and use it in GitHub Desktop.
Remove Python's smtplib CRAM-MD5 authentication method if getting SMTPAuthenticationError: (535, 'Authentication failed') and you know credentials are correct.
# settings.py
EMAIL_BACKEND = 'backends.SMTPEmailBackend'
# backends.py
"""Custom SMTP email backend class"""
import smtplib
from django.core.mail.utils import DNS_NAME
from django.core.mail.backends.smtp import EmailBackend
class SMTPEmailBackend(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
try:
# 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.host, self.port,
local_hostname=DNS_NAME.get_fqdn())
if self.use_tls:
self.connection.ehlo()
self.connection.starttls()
if self.username and self.password:
self.connection.ehlo()
self.connection.esmtp_features['auth'] = 'PLAIN LOGIN' # Remove CRAM-MD5 authentication method
self.connection.login(self.username, self.password)
return True
except:
if not self.fail_silently:
raise
@vietvudanh
Copy link
Author

When use Django mail SMTP backend, the default option use CRAM-MD5 so it's fucking failed for case when the server only accept AUTH login.
So we need this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment