Last active
August 29, 2015 14:01
-
-
Save r0yfire/34d7f76df4254a736bc3 to your computer and use it in GitHub Desktop.
Simple SendGrid email backend for Django that uses authentication tokens
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.conf import settings | |
from django.core.mail.backends.base import BaseEmailBackend | |
from django.core.mail.message import sanitize_address | |
import sendgrid | |
class SendgridBackend(BaseEmailBackend): | |
def __init__(self, user=None, token=None, **kwargs): | |
super(SendgridBackend, self).__init__() | |
self.user = user or getattr(settings, "SENDGRID_USER") | |
self.token = token or getattr(settings, "SENDGRID_TOKEN") | |
def send_messages(self, email_messages): | |
""" | |
Sends one or more EmailMessage objects and returns the number of email | |
messages sent. | |
""" | |
num_sent = 0 | |
if not email_messages: | |
return | |
for message in email_messages: | |
sent = self._send(message) | |
if sent: | |
num_sent += 1 | |
return num_sent | |
def _send(self, email_message): | |
if not email_message.recipients(): | |
return False | |
try: | |
sgrid = sendgrid.SendGridClient(self.user, self.token) | |
message = sendgrid.Mail() | |
message.set_from(sanitize_address(email_message.from_email, email_message.encoding)) | |
recipients = [sanitize_address(addr, email_message.encoding) for addr in email_message.recipients()] | |
for recipient in recipients: | |
message.add_to(recipient) | |
message.set_subject(email_message.subject) | |
message.set_from(email_message.from_email) | |
message.set_text(email_message.body) | |
status, msg = sgrid.send(message) | |
except: | |
return False | |
return True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment