Subversion Repositories SmartDukaan

Rev

Rev 1246 | Rev 5631 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

#!/usr/bin/python

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
import os
import optparse

def get_attachment_part(filename):
    part = MIMEBase('application', 'octet-stream')
    part.set_payload(open(filename, 'rb').read())
    Encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(filename))
    return part
    
def mail(from_user, from_pwd, to, subject, text, part=None):
    msg = MIMEMultipart()
    
    msg['From'] = from_user
    msg['To'] = to
    msg['Subject'] = subject
    
    msg.attach(MIMEText(text))
    
    if part:
        msg.attach(part)
    
    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
    mailServer.ehlo()
    mailServer.starttls()
    mailServer.ehlo()
    mailServer.login(from_user, from_pwd)
    mailServer.sendmail(from_user, to, msg.as_string())
    # Should be mailServer.quit(), but that crashes...
    mailServer.close()

if __name__ == '__main__':
    parser = optparse.OptionParser()
    parser.add_option("-f", "--from", dest="sender",
                   type="string",
                   help="Send the mail as this user")
    parser.add_option("-p", "--password", dest="password",
                   type="string",
                   help="Email account password of the sender")
    parser.add_option("-t", "--to", dest="to",
                   type="string",
                   help="Send the mail to this user")
    parser.add_option("-s", "--subject", dest="subject",
                   type="string",
                   help="Subject line of the email")
    parser.add_option("-x", "--text", dest="text",
                   type="string",
                   help="Email body text")
    parser.add_option("-a", "--attach", dest="attachment",
                    metavar="FILE",
                    help="send FILE as an attachment")
    parser.set_defaults(sender="help@shop2020.in", password="5h0p2o2o")
    (options, args) = parser.parse_args()
    
    if options.attachment:
        part = get_attachment_part(options.attachment)
    else:
        part = None
    
    mail(options.sender, options.password, options.to, options.subject, options.text, part)