Skip to content

Latest commit

 

History

History
107 lines (75 loc) · 3.04 KB

File metadata and controls

107 lines (75 loc) · 3.04 KB

Django Email Backend

The SparkPost python library comes with an email backend for Django.

Configure Django

To configure Django to use SparkPost, put the following configuration in settings.py file.

SPARKPOST_API_KEY = 'API_KEY'
SPARKPOST_BASE_URI = 'api.sparkpost.com'
EMAIL_BACKEND = 'sparkpost.django.email_backend.SparkPostEmailBackend'

Replace API_KEY with an actual API key.

If you are using an EU account, set SPARKPOST_BASE_URI to api.eu.sparkpost.com. The default value is api.sparkpost.com.

You can also use SPARKPOST_OPTIONS to set options that will apply to every transmission. For example:

SPARKPOST_OPTIONS = {
    'track_opens': False,
    'track_clicks': False,
    'transactional': True,
}

Sending an email

Django is now configured to use the SparkPost email backend. You can now send mail using Django's send_mail method:

from django.core.mail import send_mail

send_mail(
    subject='Hello from SparkPost',
    message='Woo hoo! Sent from Django!',
    from_email='from@yourdomain.com',
    recipient_list=['to@example.com'],
    html_message='<p>Hello Rock stars!</p>',
)

You can also use EmailMessage or EmailMultiAlternatives class directly. This allows you to set additional SparkPost fields: template, substitution_data, campaign, metadata:

email = EmailMessage(
    to=[
        {
            'address': 'to@example.com',
            'substitution_data': {
                'reward-level': 'Silver'
            },
            'metadata': {'user-id': '46576432465'}
        }
    ],
    from_email='test@from.com'
)
email.template = 'template-id'
email.substitution_data = {'season': 'Winter'}
email.metadata = {'cart-id': '74562657874'}
email.campaign = 'campaign-id'
email.send()

Or cc, bcc, reply to, or attachments fields:

from django.core.mail import EmailMultiAlternatives

email = EmailMultiAlternatives(
  subject='hello from sparkpost',
  body='Woo hoo! Sent from Django!',
  from_email='from@yourdomain.com',
  to=['to@example.com'],
  cc=['ccone@example.com'],
  bcc=['bccone@example.com'],
  reply_to=['replyone@example.com']
)

email.attach_alternative('<p>Woo hoo! Sent from Django!</p>', 'text/html')
email.attach('image.png', img_data, 'image/png')
email.send()

Supported version

SparkPost will support all versions of Django that are within extended support period. Refer to Django Supported Versions.

Additional documentation

See our Using SparkPost with Django in support article.