#!/usr/bin/python # # Quick mail user agent, usefull for unknown/unconfigured environments. # # Performs direct delivery for text message and optional attachment. # import os import sys import urllib import smtplib import string from email import Encoders from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.MIMEMultipart import MIMEMultipart class App: mail_from = '' mail_to = '' subject = '' attachment = '' message = '' debug = 0 smtp_server = 'mail.varkala.net' smtp_port = 25 def __init__( self ): self.read_data() self.send_data() def read_data( self ): prompt = self.prompt self.mail_from = prompt( 'mail from:' ) self.mail_to = prompt( 'mail to:' ) self.subject = prompt( 'subject:' ) self.attachment = prompt( 'file:' ) self.message = prompt( 'message:' ) self.validate_input() def prompt( self, msg ): return raw_input( msg + ' ' ).strip() def validate_input( self ): if self.mail_to.find( '@' ) < 0: print 'mail to is incorrect!' sys.exit( 1 ) if self.attachment: if not ( os.path.isfile( self.attachment ) and os.access( self.attachment, os.R_OK ) ): print 'unable to read attachment!' opt = self.prompt( 'do you wish to proceed without attachment[y|n]?' ).lower() if opt == 'n': sys.exit( 1 ) else: self.attachment = '' def send_data( self ): msg = self.prepare_message() # send email s = smtplib.SMTP() s.set_debuglevel( self.debug ) s.connect( self.smtp_server, self.smtp_port ) s.sendmail( self.mail_from, self.mail_to, msg.as_string() ) s.quit() print 'message delivered!' def prepare_message( self ): msg = MIMEMultipart() msg['Subject'] = self.subject msg['To'] = self.mail_to msg['From'] = self.mail_from msg.preamble = "you will not see this in a mime-aware mail reader\n" msg.epilogue = '' att = MIMEText( self.message ) msg.attach( att ) if self.attachment: f = open( self.attachment ) att = MIMEBase( 'application', 'octet-stream' ) att.set_payload( f.read() ) Encoders.encode_base64( att ) att.add_header( 'Content-Disposition', 'attachment', filename=self.get_filename() ) msg.attach( att ) f.close() return msg def get_filename( self ): return self.attachment.split( os.sep )[ -1 ] def main(): App() if __name__ == '__main__': main()