Skip to content

Instantly share code, notes, and snippets.

@perfecto25
Last active July 27, 2023 19:05
Show Gist options
  • Star 24 You must be signed in to star a gist
  • Fork 16 You must be signed in to fork a gist
  • Save perfecto25/4b79b960eb58dc1f6025b56394b51cc1 to your computer and use it in GitHub Desktop.
Save perfecto25/4b79b960eb58dc1f6025b56394b51cc1 to your computer and use it in GitHub Desktop.
Python function to send email using a Jinja HTML template
<style type="text/css">
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 300;
src: local('Open Sans Light'), local('OpenSans-Light'), url(http://fonts.gstatic.com/s/opensans/v13/DXI1ORHCpsQm3Vp6mXoaTa-j2U0lmluP9RWlSytm3ho.woff2) format('woff2');
unicode-range: U+0460-052F, U+20B4, U+2DE0-2DFF, U+A640-A69F;
}
.body {
width: 90%;
margin: auto;
font-family: 'Open Sans', 'Helvetica', sans-serif;
font-size: 14pt;
color: #075D72;
}
a:link { color: #B40057; text-decoration: underline}
a:visited { color: #542A95; text-decoration: none}
a:hover { color: #B40057; background-color:#C4FFF9; text-decoration: underline }
</style>
<div class="body">
Hello Marvel heroes, lets have a beat down at Metropolis. DO NOT bring the following items!!
{{ item1 }} - this causes Superman to puke<br>
{{ item2 }} - this causes Green Lantern to be useless
<p>
</div>
<p><br><br>
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, sender='MyCompanyName<noreply@mycompany.com>', cc=None, bcc=None, subject=None, body=None):
''' sends email using a Jinja HTML template '''
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
# convert TO into list if string
if type(to) is not list:
to = to.split()
to_list = to + [cc] + [bcc]
to_list = filter(None, to_list) # remove null emails
msg = MIMEMultipart('alternative')
msg['From'] = sender
msg['Subject'] = subject
msg['To'] = ','.join(to)
msg['Cc'] = cc
msg['Bcc'] = bcc
msg.attach(MIMEText(body, 'html'))
server = smtplib.SMTP("127.0.0.1") # or your smtp server
try:
log.info('sending email xxx')
server.sendmail(sender, to_list, msg.as_string())
except Exception as e:
log.error('Error sending email')
log.exception(str(e))
finally:
server.quit()
#------------------------------------------------------------------------------------------------
# MAIN
item1 = 'kryptonite'
item2 = 'green clothing'
# generate HTML from template
html = render_template('default.j2', **locals())
to_list = ['spiderman@marvel.com', 'punisher@marvel.com']
sender = 'superman<superman@dc.com>'
cc = 'greenlantern@dc.com'
bcc = 'invisible_man@dc.com'
subject = 'Meet me for a beatdown'
# send email to a list of email addresses
send_email(to_list, sender, cc, bcc, subject, html.encode("utf8"))
@TheEverlastingBish
Copy link

Love this. Perfecto!

@TowelDude
Copy link

Nice!
Instead of

html = render_template('default.j2', vars=locals())

You could simply do

html = render_template('default.j2', **locals())

and reference the variables directly in the template.

@perfecto25
Copy link
Author

Nice!
Instead of

html = render_template('default.j2', vars=locals())

You could simply do

html = render_template('default.j2', **locals())

and reference the variables directly in the template.

thanks ill update

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment