Simple programme - Just want to know whether this is correct way of coding

guptha gjango.py at gmail.com
Fri May 8 02:37:27 EDT 2009


Hi group,
This is my first programme in python ,I need to know whether my code
is in the right path of performance

I wrote a code using multithreading to send mails

FROM = '....com'

SUBJECT = 'This is the subject'
MSGBODY = 'This the body of the message '
MAILSERVER = 'mail....com'
port = 25
username = 'username'
password = 'pass'

# trim the strings of any leading or trailing spaces
FROM = FROM.strip()
SUBJECT = SUBJECT.strip()
MSGBODY = MSGBODY.strip()
MAILSERVER = MAILSERVER.strip()
username = username.strip()
password = password.strip()


# set up email parameters
msg = MIMEMultipart()
msg['From'] = FROM
msg['Subject'] = SUBJECT

#--------------------------------------------------
print "Starting Multi Thread Method"

class MyThread(Thread):

    def __init__(self, site,  FROM, MSGBODY):
        Thread.__init__(self)
        self.site = site
	self.FROM=FROM
	self.MSGBODY=MSGBODY

    def run(self):
	#Connect to server
	print 'Connecting to mail server ', MAILSERVER
	try:
		s = smtplib.SMTP(MAILSERVER,port)
		print 'connected'
	#s.set_debuglevel(1)
	except:
		print 'ERROR: Unable to connect to mail server', sys.exc_info	()[0]
	 	sys.exit(1)

	#login to server
	if password <> '':
		print 'Logging into mail server'
		try:
			s.login(username,password)
		except:
			print 'ERROR: Unable to login to mail server', MAILSERVER
			print 'Please recheck your password'
			sys.exit(1)
	print "running for %s " %self.site
	print s
	s.sendmail(self.FROM, self.site, self.MSGBODY)
	print "from %s" %self.FROM
	print "msg %s" %self.MSGBODY
 	print "Emailed for  site %s" %self.site
	s.quit()
	s.close()


a= time.time()
threads = []

for site in listTo:
    T = MyThread(site,FROM,MSGBODY)
    threads.append(T)
    T.start()


for i in threads:
    i.join()

print "Took %s seconds" %str(time.time()-a)

#-----------------------------------------------------

The code Works fine ,but I doubt about the performance issue ,My
intention is to send mails concurrently to large number of mail.
1.For every mail id i send It creates a new SMTP object,in case, if i
send to 1000 or more ids
      a) It obliviously creates that much SMPT connections ,is this a
right approach .
Thanks in Advance



More information about the Python-list mailing list