Python – Parse input file and Mail

Code is here. Please check for required python libraries.


import os
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from optparse import OptionParser

# Email Configuration
_email_to_ = ''
_email_sender_ = ''
_email_cc_     = [''] # A List is expected

def send_email(message, subject, sender, to, cc = None):
    ''' Function to send email message '''
    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = sender
    msg['To'] = to
    if cc:
        msg['Cc'] = ', '.join(cc)
        to = to + cc
    text = MIMEText(message,'html')
    text.add_header('Content-Disposition', 'inline')
    smtp = smtplib.SMTP('mailhost')
    smtp.sendmail(sender, to, msg.as_string())
    return msg


parser = OptionParser()
parser.add_option("-f", "--filename", dest="filename",
              help="upload one FILE", metavar="FILE")

(options, args) = parser.parse_args()

files = [str(options.filename)]

for eachfile in files: # to checks if input is provided
    if os.path.isfile(eachfile):
        message = 'Testing,............'
        subject = 'Test Mail'
        sender = _email_sender_
        to = sender
        fp = open(eachfile,'r')
        message = fp.readlines();
        message = ''.join(message);
        message = HTML_HEADER + message + HTML_FOOTER
        send_email(message, subject, sender, to)
        send_email(message, subject, sender, to)

To run this script use command as below,.

 bash-2.0:$python -f log

All the log file content will be mailed to the configured mail group.


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 )

Google+ photo

You are commenting using your Google+ 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