Skip to content

Instantly share code, notes, and snippets.

@mbiette
Created September 24, 2015 17:44
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mbiette/f75ae41f7b4557274a9f to your computer and use it in GitHub Desktop.
Save mbiette/f75ae41f7b4557274a9f to your computer and use it in GitHub Desktop.
Simple python script to send an email with a csv attached
# coding=utf-8
__author__ = 'Maxime Biette'
conf = {
'from': 'maximebiette@gmail.com',
'to': 'maximebiette+test@gmail.com',
'server': 'smtp.gmail.com',
'port': '587',
'tls': 'yes',
'login': 'maximebiette@gmail.com',
'password': '',
'subject_keyword': ''
}
report = {
'content': u'This,is,a,test,file',
'filename': 'testfile.csv'
}
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.charset import Charset, BASE64
from email.mime.nonmultipart import MIMENonMultipart
from email import charset
class Mailer:
def __init__(self, conf):
self.conf = conf
charset.add_charset('utf-8', charset.SHORTEST, charset.QP)
def send_report(self, date, short_description, additional_description, title, report):
# Create message container - the correct MIME type is multipart/mixed to allow attachment.
full_email = MIMEMultipart('mixed')
full_email['Subject'] = "[" + self.conf['subject_keyword'] + " " + date + "] " + title
full_email['From'] = self.conf['from']
full_email['To'] = self.conf['to']
# Create the body of the message (a plain-text and an HTML version).
body = MIMEMultipart('alternative')
body.attach(MIMEText((short_description + "\n\n" + additional_description).encode('utf-8'),
'plain', _charset='utf-8'))
body.attach(MIMEText(("""\
<html>
<head></head>
<body>
<p>""" + short_description + """</p><br>
""" + additional_description + """
</body>
</html>
""").encode('utf-8'),
'html', _charset='utf-8'))
full_email.attach(body)
# Create the attachment of the message in text/csv.
attachment = MIMENonMultipart('text', 'csv', charset='utf-8')
attachment.add_header('Content-Disposition', 'attachment', filename=report['filename'])
cs = Charset('utf-8')
cs.body_encoding = BASE64
attachment.set_payload(report['content'].encode('utf-8'), charset=cs)
full_email.attach(attachment)
# Send the message via SMTP server.
s = smtplib.SMTP(self.conf['server'], self.conf['port'])
if self.conf['tls'] == 'yes':
s.starttls()
if not self.conf['login'] == '':
s.login(self.conf['login'], self.conf['password'])
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail(self.conf['from'], self.conf['to'], full_email.as_string())
# self.logger.info('email sent')
s.quit()
mailer = Mailer(conf)
mailer.send_report('20150924', 'This is a test', 'nothing to report.', 'Test', report)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment