Skip to content

Instantly share code, notes, and snippets.

@koriaf
Created September 14, 2015 09:11
Show Gist options
  • Save koriaf/9dab35e0bdd11e766447 to your computer and use it in GitHub Desktop.
Save koriaf/9dab35e0bdd11e766447 to your computer and use it in GitHub Desktop.
Django-post_office email with custom template
def send_email(self,
template_name,
context={},
attachments={},
base_message_template='post_office/email_base_text.html',
base_message_template_html='post_office/email_base_html.html'):
'''
Try to send email by Django post_office library, with custom HTML template and
respect of user language.
Designed to work as method of UserProfile model, which has OneToOne relationship
with settings.AUTH_USER_MODEL and self.preffered_language attribute.
'''
try:
try:
tpl = get_email_template(name=template_name, language=self.preffered_language)
except EmailTemplate.DoesNotExist:
tpl = get_email_template(name=template_name)
context['language'] = self.preffered_language
translation_activate(self.preffered_language)
base_message = get_template(base_message_template).render(Context(context))
base_message_html = get_template(base_message_template_html).render(Context(context))
subject = tpl.subject
message = base_message.replace("MESSAGE_TEXT", tpl.content)
message_html = base_message_html.replace("MESSAGE_TEXT", tpl.html_content)
mail.send(
[self.user.email],
settings.DEFAULT_FROM_EMAIL,
subject=subject,
message=message,
html_message=message_html,
headers={
'Reply-to': 'feedback@your-domain.org',
# make sure you have this url - much better for usability and less annoyed
# users and spam filters
'List-Unsubscribe': '<https://your-domain.org/some/unsubscribe/url/>',
},
context=context,
attachments=attachments,
)
translation_deactivate()
except Exception as e:
misc_logger.exception(e)
return False
return True
@koriaf
Copy link
Author

koriaf commented May 22, 2016

It has ugly replacement of MESSAGE_TEXT and MESSAGE_TEXT, but it's fine in fact and may be easily replaced by adding {% extends ... %} in database-stored template and {% block ... %} usage.

By the way, how would it work if we add {% extends '...' %} now?..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment