Using Python to send emails with attachments

Python is a great utility programming language. One of the activities we use python for is to send automated emails at the end of a task(i.e., Cube builds, database refresh, etc.). Python can be leveraged to parse the log files and send out notifications or mine the logs to get the stats and produce visualizations.  

By default, the language includes various modules in the standard library which can be used to send several types of email ( plain text, HTML, etc.) 

Below I have listed the code for sending emails with attachments. A couple of areas where we use this notifying features are

  • Automated Cognos powerplay cube build success or failure notification with log file send an attachment.
  • Parsing the Planning Analytics log files to identify daily User Logins.

I will be writing detailed posts on getting the above-listed tasks accomplished shortly.

Send emails with attachments

import time
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import smtplib

#replace with your email ids
emails = ['']

#replace with the attachement path
payLoad = '<filepath>\filename.txt'

#enter email id you want the emails to be sent from(i.e does not have to be an actual email account) 
sender = 'SampleEmailAccount'
smtpserver = smtplib.SMTP("",25)
user = 'replace_with_userID'
password = 'replace_with_password'
smtpserver.login(user, password)
msg = MIMEMultipart()
#enter the subject of your email within double quotes.
msg['Subject'] = "Sample Email Subject Line."

#enter the body of your email in HTML format.
html = """\
                           This sample email subject line, write something meaningful here.
mailBody = MIMEText(html, 'html')
mailAttach = MIMEBase('application', "octet-stream")
mailAttach.set_payload(open(payLoad , "rb").read())
mailAttach.add_header('Content-Disposition', 'attachment', filename=payLoad)
smtpserver.sendmail(sender, emails, msg.as_string())

I have listed the link to the file in GitHub below. Let me know if you have any questions or have any issues getting it to work.

One comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s