Send email using Jinja template

to send emails from a template, create 2 functions, one to render template, 2nd to email

def render_template(template, **kwargs):

''' renders a Jinja template into HTML '''

# check if template exists

if not os.path.exists(template):

print('No template file present: %s' % template)

sys.exit()

import jinja2

templateLoader = jinja2.FileSystemLoader(searchpath="/")

templateEnv = jinja2.Environment(loader=templateLoader)

templ = templateEnv.get_template(template)

return templ.render(**kwargs)

def send_email(to, subj, html):

# Import smtplib to provide email functions

import smtplib

# Import the email modules

from email.mime.multipart import MIMEMultipart

from email.mime.text import MIMEText

from email.header import Header

from email.utils import formataddr

# Construct email

msg = MIMEMultipart('alternative')

smtp_server = '127.0.0.1'

msg['To'] = to

msg['From'] = formataddr((str(Header('My Header Here', 'utf-8')), 'myName@'+os.uname()[1]))

msg['Subject'] = subj

# Create the body of the message (a plain-text and an HTML version).

#text = "This is a test message.\nText and html."

# Record the MIME types of both parts - text/plain and text/html.

#msg.attach(MIMEText(text, 'plain'))

msg.attach(MIMEText(html, 'html'))

# send email

s = smtplib.SMTP(smtp_server)

s.sendmail('JIRA02', to, msg.as_string())

s.quit()

in __main__, render the template, vars=locals() will dump all your variables into a Hash, or you can provide specific vars, ie name=name, age=age

html = render_template(base_dir+'/plugins/'+plugin+'/templates/'+template, vars=locals())

send the email,

send_email(email, message, html.encode("utf8"))

jinja template looks like this,

{% set rn_hash = vars['rn_hash'] %}

<h1>{{ vars['msg'].upper() }} </h1>

<p>

{{ vars['email_text'] }}

{% for rn_key in rn_hash %}

{{ rn_key }}

{% endfor %}