I have one python script which I want to execute as a daily cron job to send emails to all users. Currently I have hard-coded the html inside the script and it looks dirty. I have read the docs, but I haven't figured out how can I render the template within my script.
Is there any way that I can have the separate html file with placeholders which I can use python to populate and then send as the email's body?
I want something like this:
mydict = {}
template = '/templates/email.j2'
fillTemplate(mydict)
html = getHtml(filledTemplate)
3 Answers 3
I am going to expand on @Mauro's answer. You would move all of the email HTML and/or text into a template file(s). Then use the Jinja API to read the template in from the file; finally, you would render the template by providing the variables that are in the template.
# copied directly from the docs
from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('yourapplication', 'templates'))
template = env.get_template('mytemplate.html')
print template.render(the='variables', go='here')
This is a link to an example of using the API with the template.
Comments
I was looking to do the same thing using Jinja within the Flask framework. Here's an example borrowed from Miguel Grinberg's Flask tutorial:
from flask import render_template
from flask.ext.mail import Message
from app import mail
subject = 'Test Email'
sender = '[email protected]'
recipients = ['[email protected]']
msg = Message(subject, sender=sender, recipients=recipients)
msg.body = render_template('emails/test.txt', name='Bob')
msg.html = render_template('emails/test.html', name='Bob')
mail.send(msg)
It assumes something like the following templates:
templates/emails/test.txt
Hi {{ name }},
This is just a test.
templates/emails/test.html
<p>Hi {{ name }},</p>
<p>This is just a test.</p>
1 Comment
flask.render_template_string if you want to pass a string.You can use Jinja2, a template language for Python. It has template inheritance feature. Look at this example from official docs.