Skip to content

Instantly share code, notes, and snippets.

@xals
Last active June 28, 2018 12:40
Show Gist options
  • Save xals/e00c2a3789bceda0a07a4276ff8ebf4b to your computer and use it in GitHub Desktop.
Save xals/e00c2a3789bceda0a07a4276ff8ebf4b to your computer and use it in GitHub Desktop.
Simple python3 program to send email from a Jinja2 template and a CSV datasource
This is a simple Python3 program, using a CSV file with headers as datasource. Column names are injected in the template rendering to be used as variable substitution.
This is not perfect. For example, the encoding fails for address headers when there are some accentuated characters (éèà for example) in the firsname or the lastname.
The template can contain UTF-8 characters, the message is Base64 encoded before beeing sent.
firstname lastname address password
Firstname Lastname firstname.lastname@example.com password
#!/usr/bin/env python3
import csv
from email import message_from_string
from email.utils import formatdate, parseaddr, make_msgid
from smtplib import SMTP
from jinja2 import Environment, PackageLoader
def main():
# Initialize Jinja2 environment and template
env = Environment(loader=PackageLoader('emailing', '.'))
template = env.get_template('template.eml.j2')
# Open CSV file
with open('accounts.csv', 'r', newline='', encoding='utf-8') as f:
for row in csv.DictReader(f, dialect=csv.unix_dialect):r
# Render template
text = template.render(**row)
# Prepare message
message = message_from_string(text)
# Add date and message ID
message['Date'] = formatdate()
message['Message-ID'] = make_msgid()
# Set charset
message.set_charset('utf-8')
# Send message
with SMTP(host='smtp.sysnove.fr', port=587) as smtp:
smtp.starttls()
smtp.login('alexis@sysnove.fr', 'password')
smtp.send_message(message)
if __name__ == '__main__':
main()
From: "Alexis Lahouze" <alexis@sysnove.fr>
To: "{{ firstname }} {{ lastname }}" <{{ address }}>
Subject: Here is a mail to {{ address }}
Hi {{ firstname }},
Greetings from Alexis.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment