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 = ['john.doe@acme.com']
#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("smtp.ADDomain.com",25)
user = 'replace_with_userID'
password = 'replace_with_password'
smtpserver.ehlo()
smtpserver.ehlo
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 = """\
<html>
<head>
</head>
<body>
This sample email subject line, write something meaningful here.
</body>
</html>
"""
mailBody = MIMEText(html, 'html')
mailAttach = MIMEBase('application', "octet-stream")
mailAttach.set_payload(open(payLoad , "rb").read())
mailAttach.add_header('Content-Disposition', 'attachment', filename=payLoad)
msg.attach(mailAttach)
msg.attach(mailBody)
smtpserver.sendmail(sender, emails, msg.as_string())
smtpserver.close()
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