diff --git a/EmailClient.py b/EmailClient.py index cffb248..6396e4d 100644 --- a/EmailClient.py +++ b/EmailClient.py @@ -9,6 +9,8 @@ from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.encoders import encode_base64 +from mako.template import Template as MakoTemplate + log = logging.getLogger(__name__) @@ -83,21 +85,27 @@ class EmailClient(object): msg['Date'] = email.utils.formatdate(None, True) encoding = encoding if encoding else self.encoding if template: - assert template in templates, "Unknwon template %s" % template + assert template in self.templates, "Unknwon template %s" % template # Handle subject from template if not subject: - assert templates[template].get('subject'), 'No subject defined in template %s' % template - msg['Subject'] = templates[template]['subject'].format(**template_vars) + assert self.templates[template].get('subject'), 'No subject defined in template %s' % template + msg['Subject'] = self.templates[template]['subject'].format(**template_vars) # Put HTML part in last one to prefered it parts = [] - if templates[template].get('text'): - parts.append((templates[template].get('text'), 'plain')) - if templates[template].get('html'): - parts.append((templates[template].get('html'), 'html')) + if self.templates[template].get('text'): + if isinstance(self.templates[template]['text'], MakoTemplate): + parts.append((self.templates[template]['text'].render(**template_vars), 'plain')) + else: + parts.append((self.templates[template]['text'].format(**template_vars), 'plain')) + if self.templates[template].get('html'): + if isinstance(self.templates[template]['html'], MakoTemplate): + parts.append((self.templates[template]['html'].render(**template_vars), 'html')) + else: + parts.append((self.templates[template]['html'].format(**template_vars), 'html')) for body, mime_type in parts: - msg.attach(MIMEText(body.format(**template_vars).encode(encoding), mime_type, _charset=encoding)) + msg.attach(MIMEText(body.encode(encoding), mime_type, _charset=encoding)) else: assert subject, 'No subject provided' if text_body: @@ -313,6 +321,13 @@ if __name__ == '__main__': help="Test email recipient", ) + test_opts.add_argument( + '-m', '--mako', + action="store_true", + dest="test_mako", + help="Test mako templating", + ) + options = parser.parse_args() if not options.test_to: @@ -340,8 +355,14 @@ if __name__ == '__main__': templates = dict( test=dict( subject="Test email", - text="Just a test email sent at {sent_date}.", - html="Just a test email." + text=( + "Just a test email sent at {sent_date}." if not options.test_mako else + MakoTemplate("Just a test email sent at ${sent_date}.") + ), + html=( + "Just a test email. (sent at {sent_date})" if not options.test_mako else + MakoTemplate("Just a test email. (sent at ${sent_date})") + ) ) )