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)
Use jinja2. Template. globals to call a function in a jinja2 template. Create a format string that applies a function by calling "{{ func(input) }}" apply the function func to input .
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With