Skip to content

Instantly share code, notes, and snippets.

@dzhuang
Forked from niran/mail.py
Created September 8, 2016 15:51
Show Gist options
  • Save dzhuang/d23cc00589428951aab8ce1e1630c579 to your computer and use it in GitHub Desktop.
Save dzhuang/d23cc00589428951aab8ce1e1630c579 to your computer and use it in GitHub Desktop.
Multiple email connections in Django
from django.conf import settings
import django.core.mail
class MissingConnectionException(Exception):
pass
def get_connection(label=None, **kwargs):
if label is None:
label = getattr(settings, 'EMAIL_CONNECTION_DEFAULT', None)
try:
connections = getattr(settings, 'EMAIL_CONNECTIONS')
options = connections[label]
except KeyError, AttributeError:
raise MissingConnectionException(
'Settings for connection "%s" were not found' % label)
options.update(kwargs)
return django.core.mail.get_connection(**options)
EMAIL_CONNECTIONS = {
'gmail': {
'host': 'smtp.gmail.com',
'username': '[email protected]',
'password': 'password',
'port': 587,
'use_tls': True,
},
'socketlabs': {
'host': 'smtp.socketlabs-od.com',
'username': 'blah',
'password': 'password',
'use_tls': False,
},
'ses': {
'backend': 'django_ses.SESBackend',
},
'distributed': {
'backend': 'tt.mail.backends.distributed.DistributedBackend',
'components': (
# Use SES for 8% of our emails. We send about 10,000 per day, so
# 8% should keep us under our initial quota of 1,000.
('ses', 0.08),
('socketlabs', 0.92),
),
}
}
EMAIL_CONNECTION_DEFAULT = 'distributed'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment