Skip to content

Instantly share code, notes, and snippets.

@martinrusev
Forked from iamit/gist:5415771
Last active August 29, 2015 14:14
Show Gist options
  • Save martinrusev/4d300afd6c551d8b6a02 to your computer and use it in GitHub Desktop.
Save martinrusev/4d300afd6c551d8b6a02 to your computer and use it in GitHub Desktop.
"""
Django's SMTP EmailBackend doesn't support an SMTP_SSL connection necessary to interact with Amazon SES's newly announced SMTP server. We need to write a custom EmailBackend overriding the default EMailBackend's open(). Thanks to https://github.com/bancek/django-smtp-ssl for the example.
"""
--- settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'email-smtp.us-east-1.amazonaws.com'
EMAIL_PORT = 465
EMAIL_HOST_USER = 'username'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_USE_TLS = False # NOTE: this is for using START_TLS: no need if using smtp over ssl
--- shell
>>> from django.core.mail import send_mail
>>> send_mail('subject', 'message', '[email protected]', ['[email protected]'])
SMTPServerDisconnected: Connection unexpectedly closed
--- settings.py
EMAIL_BACKEND = 'backends.smtp.SSLEmailBackend'
# Adding another EMAIL OPTION:
EMAIL_USE_SSL = True #custom setting to make this backend usable for both SMTP and SMTP over SSL
EMAIL_SMTP_TIMEOUT_SECONDS = 10 #custom setting to make playing with timeouts a bit easier
--- backends/smtp.py
import smtplib
from django.conf import settings
from django.core.mail.utils import DNS_NAME
from django.core.mail.backends.smtp import EmailBackend
class SSLEmailBackend(EmailBackend):
def open(self):
if self.connection:
return False
try:
if settings.EMAIL_USE_SSL:
self.connection = smtplib.SMTP_SSL(host=self.host, port=self.port,
local_hostname=local_hostname, timeout=settings.EMAIL_SMTP_TIMEOUT_SECONDS)
else:
self.connection = smtplib.SMTP(host=self.host, port=self.port,
local_hostname=DNS_NAME.get_fqdn(),timeout=settings.EMAIL_SMTP_TIMEOUT_SECONDS)
# Note: you don't want to use START_TLS in case over SSL
if self.use_tls:
self.connection.ehlo()
self.connection.starttls()
self.connection.ehlo()
self.connection = smtplib.SMTP_SSL(self.host, self.port,
local_hostname=DNS_NAME.get_fqdn())
if self.username and self.password:
self.connection.login(self.username, self.password)
return True
except:
if not self.fail_silently:
raise
--- shell
>>> from django.core.mail import send_mail
>>> send_mail('subject', 'message', '[email protected]', ['[email protected]'])
1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment