Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added personalization and i18n features #16

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
# Distribution
build/
dist/
django_templated_mail.egg-info

# Byte-compiled / optimized / DLL files
__pycache__/
Expand Down Expand Up @@ -36,4 +37,7 @@ ENV/
*.DS_Store

# logs
*.log
*.log

# vim
*.swp
1 change: 1 addition & 0 deletions docs/source/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ Welcome to django-templated-mail documentation!
settings
templates_syntax
sample_usage
personalization

Indices and tables
==================
Expand Down
34 changes: 34 additions & 0 deletions docs/source/personalization.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
Personalizing e-mails
========================



Interpolating user data
------------------------------

If you want to put some personal data of your user in the e-mail, you may use
the ``user`` variable in your context. To use this variable you either need to
pass the ``request`` object when creating the ``BaseEmailMessage``:

.. code-block:: python
email_message = BaseEmailMessage(
request=request,
template_name='personalized_mail.html'
)

or you need to specify actual user objects in the `to` field:

.. code-block:: python
email_message.send(to=[user1, user2], single_email=False)

i18n
------

Django features some pretty nice i18n mechanism, but it can be insufficient
when emailing your users. Your e-mails will ofter be sent from inside a celery
task, where the ``request`` object is not accessible. If you still want to
translate the e-mail for your userbase, you need to specify the `locale_field`
value in your settings. This value should point to a field (or a property)
on your user models that contains their locale (it is up to you,
how do you populate this field). If you then send personalized emails, as
described above, they will be translated to your users' locales.
18 changes: 15 additions & 3 deletions docs/source/settings.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,12 @@ You may optionally provide following settings:

.. code-block:: python

'DOMAIN': 'example.com'
'SITE_NAME': 'Foo Website'
'TEMPLATED_MAIL': {
'DOMAIN': 'example.com',
'SITE_NAME': 'Foo Website',
LOCALE_FIELD: 'locale',
}


DOMAIN
------
Expand All @@ -25,4 +29,12 @@ Used in email template context. Usually it will contain the desired title of you
app. If not provided the current site's name will be used.


**Default**: ``False``
**Required**: ``False``

LOCALE_FIELD
------------------

The field on a user model that contains the locale name to be used. If not
specified, the per-user i18n is disabled.

**Required**: ``False``
8 changes: 8 additions & 0 deletions manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import os
import sys

if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests.settings")
from django.core.management import execute_from_command_line
args = sys.argv
execute_from_command_line(args)
1 change: 1 addition & 0 deletions requirements/base
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
django>=1.8
six==1.12.0
3 changes: 2 additions & 1 deletion requirements/test
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ flake8==3.4.1
pytest==3.2.2
pytest-cov==2.5.1
pytest-django==3.1.2
pytest-pythonpath==0.7.1
pytest-pythonpath==0.7.1
six==1.12.0
98 changes: 80 additions & 18 deletions templated_mail/mail.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,38 @@
import copy
import contextlib
import six

from django.conf import settings
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.sites.shortcuts import get_current_site
from django.core import mail
from django.utils import translation
from django.template.context import make_context
from django.template.loader import get_template
from django.template.loader_tags import BlockNode, ExtendsNode
from django.views.generic.base import ContextMixin


LOCALE_FIELD = getattr(
settings, 'TEMPLATED_MAIL', {}
).get('locale_field', None)


@contextlib.contextmanager
def translation_context(language):
prev_language = translation.get_language()
try:
translation.activate(language)
yield
finally:
translation.activate(prev_language)


@contextlib.contextmanager
def nullcontext():
yield


class BaseEmailMessage(mail.EmailMultiAlternatives, ContextMixin):
_node_map = {
'subject': 'subject',
Expand All @@ -25,8 +51,9 @@ def __init__(self, request=None, context=None, template_name=None,

if template_name is not None:
self.template_name = template_name
self.is_rendered = False

def get_context_data(self, **kwargs):
def get_context_data(self, user=None, **kwargs):
ctx = super(BaseEmailMessage, self).get_context_data(**kwargs)
context = dict(ctx, **self.context)
if self.request:
Expand All @@ -40,14 +67,14 @@ def get_context_data(self, **kwargs):
site_name = context.get('site_name') or (
getattr(settings, 'SITE_NAME', '') or site.name
)
user = context.get('user') or self.request.user
user = user or context.get('user') or self.request.user
else:
domain = context.get('domain') or getattr(settings, 'DOMAIN', '')
protocol = context.get('protocol') or 'http'
site_name = context.get('site_name') or getattr(
settings, 'SITE_NAME', ''
)
user = context.get('user')
user = user or context.get('user')

context.update({
'domain': domain,
Expand All @@ -57,27 +84,62 @@ def get_context_data(self, **kwargs):
})
return context

def render(self):
context = make_context(self.get_context_data(), request=self.request)
def render(self, user=None):
if self.is_rendered:
return
context = make_context(
self.get_context_data(user),
request=self.request,
)
if user is None or LOCALE_FIELD is None:
language_context = nullcontext()
else:
language_context = translation_context(
getattr(user, LOCALE_FIELD)
)
template = get_template(self.template_name)
with context.bind_template(template.template):
with language_context, context.bind_template(template.template):
blocks = self._get_blocks(template.template.nodelist, context)
for block_node in blocks.values():
self._process_block(block_node, context)
self._attach_body()
self.is_rendered = True

def send(self, to, *args, **kwargs):
self.render()

self.to = to
self.cc = kwargs.pop('cc', [])
self.bcc = kwargs.pop('bcc', [])
self.reply_to = kwargs.pop('reply_to', [])
self.from_email = kwargs.pop(
'from_email', settings.DEFAULT_FROM_EMAIL
)

super(BaseEmailMessage, self).send(*args, **kwargs)
def send(self, to, single_email=True, *args, **kwargs):
if single_email:
self.render()
to_emails = []
for recipient in to:
if isinstance(recipient, AbstractBaseUser):
to_emails.append(recipient.email)
elif isinstance(recipient, six.string_types):
to_emails.append(recipient)
else:
raise TypeError(
'The `to` argument should contain strings or users'
)
self.to = to_emails
self.cc = kwargs.pop('cc', [])
self.bcc = kwargs.pop('bcc', [])
self.reply_to = kwargs.pop('reply_to', [])
self.from_email = kwargs.pop(
'from_email', settings.DEFAULT_FROM_EMAIL
)
super(BaseEmailMessage, self).send(*args, **kwargs)
else:
for recipient in to:
email = copy.copy(self)
if isinstance(recipient, AbstractBaseUser):
email_to = [recipient.email]
email.render(user=recipient)
elif isinstance(recipient, six.string_types):
email_to = [recipient]
email.render()
else:
raise TypeError(
'The `to` argument should contain strings or users'
)
email.send(to=email_to, *args, **kwargs)

def _process_block(self, block_node, context):
attr = self._node_map.get(block_node.name)
Expand Down
23 changes: 23 additions & 0 deletions tests/locale/ka_GE/LC_MESSAGES/django.po
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2019-03-08 15:35+0000\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <[email protected]>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"

#: tests/templates/personalized_mail.html:4
#: tests/templates/personalized_mail.html:5
msgid "Hello"
msgstr "გამარჯობა"
23 changes: 23 additions & 0 deletions tests/locale/pl_PL/LC_MESSAGES/django.po
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2019-04-01 09:54+0000\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <[email protected]>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"

#: tests/templates/personalized_mail.html:4
#: tests/templates/personalized_mail.html:5
msgid "Hello"
msgstr "Cześć"
45 changes: 45 additions & 0 deletions tests/migrations/0001_create_user_type.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Generated by Django 2.1.7 on 2019-03-07 15:21

import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.utils.timezone


class Migration(migrations.Migration):

initial = True

dependencies = [
('auth', '0001_initial'),
]

operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')),
('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')),
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('locale', models.CharField(max_length=5)),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'verbose_name': 'user',
'verbose_name_plural': 'users',
'abstract': False,
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
]
33 changes: 33 additions & 0 deletions tests/migrations/0002_create_test_users.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# -*- coding: utf-8 -*-
# Generated by Django 2.1.7 on 2019-03-07 15:23

from django.db import migrations


def create_test_users(apps, schema_editor):
User = apps.get_model('tests', 'User')
for username, email, first_name, last_name, locale in [
('johnny', '[email protected]', 'John', 'Smith', 'en-us'),
('janek', '[email protected]', 'Jan', 'Kowalski', 'pl-pl'),
('giorgi', '[email protected]', 'გიორგი', 'ბერიძე', 'ka-ge'),
]:
User.objects.create(
username=username,
email=email,
first_name=first_name,
last_name=last_name,
locale=locale,
)


class Migration(migrations.Migration):

dependencies = [
('tests', '0001_create_user_type'),
]

operations = [
migrations.RunPython(
create_test_users, reverse_code=migrations.RunPython.noop
)
]
Empty file added tests/migrations/__init__.py
Empty file.
6 changes: 6 additions & 0 deletions tests/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.db import models
from django.contrib.auth.models import AbstractUser


class User(AbstractUser):
locale = models.CharField(max_length=5)
Loading