Last active
May 26, 2017 15:51
-
-
Save alexphelps/ac3db1c533285f98be0bc111a7f1b5ed to your computer and use it in GitHub Desktop.
Django Email with Premailer
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
from premailer import Premailer | |
from django.conf import settings | |
from django.core.mail import EmailMultiAlternatives | |
from django.dispatch import receiver, Signal | |
from django.shortcuts import get_object_or_404 | |
from django.template import loader | |
from django.template.loader import get_template | |
from django.contrib.auth.models import User | |
from .utils import get_mailchimp_api | |
""" | |
Dont copy and paste, this is just a guide on how to use Django | |
Signals, EmailMultiAlternatives and Premailer together. | |
""" | |
welcome_notification = Signal(providing_args=['user_id']) | |
@receiver(welcome_notification) | |
def send_welcome_notificatoin(sender, user_id, **kwargs): | |
user = get_object_or_404(User, pk=user_id) | |
user_email = user.email | |
context_dict = { | |
'user': user, | |
} | |
subject_template_name = 'email/welcome-notification-subject.txt' | |
subject = loader.render_to_string( | |
subject_template_name, context_dict | |
) | |
subject = ''.join(subject.splitlines()) | |
from_email = settings.SUPPORT_FROM_EMAIL | |
template_url = 'email/welcome-notification-email.html' | |
html_template = get_template(template_url) | |
html_content = Premailer( | |
html_template.render(context_dict), | |
base_url=settings.SITE_URL, | |
remove_classes=False, | |
strip_important=False | |
).transform() | |
email = EmailMultiAlternatives( | |
subject, | |
'', | |
from_email, | |
[user_email] | |
) | |
email.attach_alternative(html_content, 'text/html') | |
email.send() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment