Login

Newsletter email template

Author:
jibbolo
Posted:
September 7, 2011
Language:
Python
Version:
1.2
Score:
0 (after 0 ratings)

You can use this class for render and send html email message with the same logic and facility of website page creation. Just create an html template file with the same name of Class in lowercase.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#!/usr/bin/env python
# encoding: utf-8
"""
You can use this class for render and send html email message with the same
logic and facility of website page creation. Just create an html template file
with the same name of Class in lowercase.
"""

from django.core.mail import EmailMessage
from django.template.loader import render_to_string
from django.template import TemplateDoesNotExist
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.utils.translation import ugettext as _

class EmailError(Exception): pass

class JibEmailMessage(EmailMessage):

    context = {
        "site": Site.objects.get_current(),
    }
    subject = _("Message from portal")
    to_admins = False
    
    def __init__(self, recipient=None, headers={}, *args, **kwargs):
        _subject = self.subject
        super(JibEmailMessage, self).__init__(headers=headers, *args, **kwargs)
        self.subject = _subject
        self._set_recipient(recipient)
        self.headers = headers
    
    def _render_body(self):
        """this method render template file with the same name of class and return rendered text"""
        
        # this method i availabled only for inherited classes
        if self.__class__ != JibEmailMessage:
            
            # search file with class name in lowercase in email directory
            body_template = "email/%s.html" % (self.__class__.__name__.lower(),)
            try:
                # render_to_string is django function for rendering template from
                # file. self.context is a dict with variables that will be rendered
                # in email body
                self.body = render_to_string(body_template,self.context)
            except TemplateDoesNotExist,e:
                raise EmailError(e)
        else:
            raise EmailError("You can't render JibEmailMessage parent class")
    
    def _set_recipient(self, recipient):
        """Set the email recipient fetching email address from django user instance"""
        if recipient and isinstance(recipient, User):
            self.to.append(recipient.email)
            self.recipient = recipient
            return
        # if True the email will send to MANAGERS set in django settings
        if self.to_admins:
            for manager in MANAGERS:
                self.to.append(manager[1])            
            return
        raise EmailError("Only Django User instance accepted")

    def retrieve_recipient_info(self): 
        """This method is for inherited classes"""
        pass
        
    def send(self, *args, **kwargs):
        """
        This is a redefinition of parent class EmailMessage send method. Before sending data,
        i need to update context dict and render email body
        """
        self.retrieve_recipient_info()
        self._render_body()
        if self.body:
            return super(JibEmailMessage,self).send(*args, **kwargs)
    
    def message(self, *args, **kwargs):
        """
        This is a redefinition of parent class EmailMessage message method. Before showing data,
        i need to update context dict and render email body
        """
        self.retrieve_recipient_info()
        self._render_body()
        return super(JibEmailMessage,self).message(*args, **kwargs)

# EXAMPLES        
        
class SignupActivationEmail(JibEmailMessage): 
    
    subject = _("Activate Your Account")
    
    def __init__(self, recipient, token, *args, **kwargs):
        super(SignupActivationEmail, self).__init__(recipient, *args, **kwargs)
        self.token = token
        
    def retrieve_recipient_info(self):
        self.context.update({
            "username": self.recipient.username,
            "token": self.token,
        })
        
        
class ContactUserEmail(JibEmailMessage): 
    
    subject = _("Message from %s")
    
    def __init__(self, sender, recipient, message, time, headers={}, *args, **kwargs):
        super(ContactUserEmail, self).__init__(recipient, headers, *args, **kwargs)
        self.sender = sender
        self.context.update({
            "message":message,
            "time":time,
        })
        
    def retrieve_recipient_info(self):
        if "%s" in  self.subject:
            self.subject = self.subject % self.sender.username
        self.context.update({
            "username": self.sender.username,
        })

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.