Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save algotrader-dotcom/afcd8805087d3ca782a413c683968a8b to your computer and use it in GitHub Desktop.

Select an option

Save algotrader-dotcom/afcd8805087d3ca782a413c683968a8b to your computer and use it in GitHub Desktop.
Python Script Send Email With Attachments
#!/usr/bin/python
import smtplib
import base64
filename = "python-sendmail.py"
# Read a file and encode it into base64 format
fo = open(filename, "rb")
filecontent = fo.read()
encodedcontent = base64.b64encode(filecontent) # base64
sender = 'thuan.nguyen@pycogroup.com'
reciever = 'thuan.nguyen@pycogroup.com'
marker = "AUNIQUEMARKER"
body ="""
This is a test email to send an attachement.
"""
# Define the main headers.
part1 = """From: Thuan Nguyen <thuan.nguyen@pycogroup.com>
To: To Person <thuan.nguyen@pycogroup.com>
Subject: Sending Attachement
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (marker, marker)
# Define the message action
part2 = """Content-Type: text/plain
Content-Transfer-Encoding:8bit
%s
--%s
""" % (body,marker)
# Define the attachment section
part3 = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename=%s
%s
--%s--
""" %(filename, filename, encodedcontent, marker)
message = part1 + part2 + part3
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, reciever, message)
print "Successfully sent email"
except Exception:
print "Error: unable to send email"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment