Skip to content

Instantly share code, notes, and snippets.

@d-schmidt
Last active March 3, 2017 13:49
Show Gist options
  • Save d-schmidt/4cd317107e6080d829f5e65be42b91b8 to your computer and use it in GitHub Desktop.
Save d-schmidt/4cd317107e6080d829f5e65be42b91b8 to your computer and use it in GitHub Desktop.
sending text mails from python with text attachments
#!/usr/bin/env python3
# this is python 2 and 3 compatible
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import datetime
COMMASPACE = ', '
sender = 'sender@example.com'
recipients = ['userA@example.com', 'userB@example.com']
subject = 'Hello World'
body = """Hello Users,
your csv file"""
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = COMMASPACE.join(recipients)
msg.preamble = subject # for clients without multipart support
# attachment file(s)
filename = "important.csv"
with open(filename, "r") as text_file:
attachment = MIMEText(text_file.read())
attachment.add_header('Content-Disposition', 'attachment', filename=filename)
msg.attach(attachment)
#body
msg.attach(MIMEText(body, 'plain'))
s = smtplib.SMTP('localhost')
s.sendmail(sender, recipients, msg.as_string())
s.quit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment