feat: Send welcome email from template

This commit is contained in:
James Graham
2020-04-28 15:17:58 +01:00
parent a39cf0e7ca
commit 567322c0af
6 changed files with 100 additions and 1 deletions

View File

@@ -157,6 +157,7 @@ THIRD_PARTY_APPS = [
'django_countries', 'django_countries',
'django_select2', 'django_select2',
'rest_framework', 'rest_framework',
'post_office',
] ]
FIRST_PARTY_APPS = [ FIRST_PARTY_APPS = [
@@ -378,12 +379,15 @@ else:
# Import customisation app settings if present # Import customisation app settings if present
CUSTOMISATION_NAME = None
TEMPLATE_NAME_INDEX = 'index.html' TEMPLATE_NAME_INDEX = 'index.html'
TEMPLATE_WELCOME_EMAIL_NAME = 'welcome-email'
try: try:
from custom.settings import ( from custom.settings import (
CUSTOMISATION_NAME, CUSTOMISATION_NAME,
TEMPLATE_NAME_INDEX TEMPLATE_NAME_INDEX,
TEMPLATE_WELCOME_EMAIL_NAME
) )
logger.info("Loaded customisation app: %s", CUSTOMISATION_NAME) logger.info("Loaded customisation app: %s", CUSTOMISATION_NAME)

View File

@@ -0,0 +1 @@
default_app_config = 'people.apps.PeopleConfig'

View File

@@ -1,5 +1,63 @@
import logging
from django.apps import AppConfig from django.apps import AppConfig
from django.conf import settings
from django.core import serializers
from django.db.models.signals import post_save
logger = logging.getLogger(__name__)
def load_welcome_template_fixture(fixture_path) -> bool:
"""Load welcome email template from a JSON fixture."""
try:
with open(fixture_path) as f:
for deserialized in serializers.deserialize('json', f):
if deserialized.object.name == settings.TEMPLATE_WELCOME_EMAIL_NAME:
deserialized.save()
logger.warning('Welcome email template \'%s\' loaded', deserialized.object.name)
return True
return False
except FileNotFoundError:
logger.warning('Email template fixture not found.')
return False
def send_welcome_email(sender, instance, **kwargs):
from post_office import models
try:
instance.send_welcome_email()
except models.EmailTemplate.DoesNotExist:
logger.warning('Welcome email template \'%s\' not found - attempting to load from fixtures',
settings.TEMPLATE_WELCOME_EMAIL_NAME)
is_loaded = False
if settings.CUSTOMISATION_NAME:
# Customisation app present - try here first
is_loaded |= load_welcome_template_fixture(
settings.BASE_DIR.joinpath('custom', 'fixtures', 'email_templates.json')
)
# |= operator shortcuts - only try here if we don't already have it
is_loaded |= load_welcome_template_fixture(
settings.BASE_DIR.joinpath('people', 'fixtures', 'email_templates.json')
)
if is_loaded:
instance.send_welcome_email()
else:
logger.error('Welcome email template \'%s\' not found', settings.TEMPLATE_WELCOME_EMAIL_NAME)
class PeopleConfig(AppConfig): class PeopleConfig(AppConfig):
name = 'people' name = 'people'
def ready(self) -> None:
# Activate signal handlers
post_save.connect(send_welcome_email,
sender='people.user')

View File

@@ -0,0 +1,16 @@
[
{
"model": "post_office.emailtemplate",
"fields": {
"name": "welcome-email",
"description": "Default welcome email template",
"created": "2020-04-27T12:13:30.448Z",
"last_updated": "2020-04-27T14:45:27.152Z",
"subject": "Welcome to {{settings.PROJECT_LONG_NAME}}",
"content": "Dear {{ user.get_full_name }},\r\n\r\nWelcome to {{ settings.PROJECT_LONG_NAME }}.\r\n\r\nThanks,\r\n\r\nThe {{ settings.PROJECT_LONG_NAME }} team",
"html_content": "<h1>{{ settings.PROJECT_LONG_NAME }}</h1>\r\n\r\nDear {{ user.get_full_name }},\r\n\r\nWelcome to {{ settings.PROJECT_LONG_NAME }}.\r\n\r\nThanks,\r\n\r\nThe {{ settings.PROJECT_LONG_NAME }} team",
"language": "",
"default_template": null
}
}
]

View File

@@ -5,6 +5,8 @@ from django.urls import reverse
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django_countries.fields import CountryField from django_countries.fields import CountryField
from django_settings_export import settings_export
from post_office import mail
from backports.db.models.enums import TextChoices from backports.db.models.enums import TextChoices
@@ -28,6 +30,22 @@ class User(AbstractUser):
""" """
return hasattr(self, 'person') return hasattr(self, 'person')
def send_welcome_email(self):
"""Send a welcome email to a new user."""
# Get exported data from settings.py first
context = settings_export(None)
context.update({
'user': self,
})
mail.send(
[self.email],
sender=settings.DEFAULT_FROM_EMAIL,
template=settings.TEMPLATE_WELCOME_EMAIL_NAME,
context=context,
priority='now' # Send immediately - don't add to queue
)
class Organisation(models.Model): class Organisation(models.Model):
""" """

View File

@@ -9,11 +9,13 @@ django-countries==5.5
django-dbbackup==3.2.0 django-dbbackup==3.2.0
django-filter==2.2.0 django-filter==2.2.0
django-picklefield==2.1.1 django-picklefield==2.1.1
django-post-office==3.4.0
django-select2==7.2.0 django-select2==7.2.0
django-settings-export==1.2.1 django-settings-export==1.2.1
djangorestframework==3.11.0 djangorestframework==3.11.0
dodgy==0.2.1 dodgy==0.2.1
isort==4.3.21 isort==4.3.21
jsonfield==3.1.0
lazy-object-proxy==1.4.3 lazy-object-proxy==1.4.3
mccabe==0.6.1 mccabe==0.6.1
mysqlclient==1.4.6 mysqlclient==1.4.6