Created
March 29, 2020 15:46
-
-
Save tomoconnor/dbe06e35a1327f42c93fb2f88e06a5be to your computer and use it in GitHub Desktop.
Django Email Backend for Gov Notify
This file contains hidden or 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
""" | |
Backend for Gov.Notify | |
""" | |
from django.core import mail | |
from django.core.mail.backends.base import BaseEmailBackend | |
from notifications_python_client.notifications import NotificationsAPIClient | |
from django.conf import settings | |
class GovNotifyEmailBackend(BaseEmailBackend): | |
def __init__(self, fail_silently=False, **kwargs): | |
self.fail_silently = fail_silently | |
self.api_key = settings.GOV_NOTIFY_API_KEY | |
self.template_id = settings.GOV_NOTIFY_EMAIL_TEMPLATE_ID | |
self.notifications_client = NotificationsAPIClient(self.api_key) | |
def open(self): | |
pass | |
def close(self): | |
pass | |
def __enter__(self): | |
try: | |
self.open() | |
except Exception: | |
self.close() | |
raise | |
return self | |
def __exit__(self, exc_type, exc_value, traceback): | |
self.close() | |
def send_messages(self, email_messages): | |
""" | |
Send one or more EmailMessage objects and return the number of email | |
messages sent. | |
""" | |
msg_count = 0 | |
for message in email_messages: | |
for recipient in message.recipients(): | |
response = self.notifications_client.send_email_notification( | |
email_address = recipient, | |
template_id = self.template_id, | |
personalisation = { | |
'subject': message.subject, | |
'body': message.body | |
} | |
) | |
msg_count += 1 | |
return msg_count | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment