Package park :: Package util :: Module mail

Source Code for Module park.util.mail

 1  # This program is public domain 
 2  """ 
 3  Support for sending and receiving mail. 
 4   
 5  The Server class and send function are small wrappers around smtplib and 
 6  smtpd which make it easy for applications to send and receive mail. 
 7   
 8  Example 
 9  ======= 
10   
11  The following example prints messages on the console as they arrive:: 
12   
13   
14  """ 
15   
16  import smtplib 
17  import asyncore 
18  import threading 
19  import smtpd 
20   
21 -def send(sender, receivers, message, subject='no subject', server='localhost'):
22 """ 23 Send an email message to a group of receivers 24 """ 25 26 if ':' in server: 27 host,port = server.split(':') 28 port = int(port) 29 else: 30 host,port = server,25 31 header="From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" 32 header %= sender,", ".join(receivers),subject 33 #print "Sending the following mail message:\n"+header+message 34 #print "Trying to connect to",host,port 35 smtp = smtplib.SMTP(host,port) 36 print "Connection established" 37 smtp.sendmail(sender,receivers,header+message) 38 print "Mail sent from",sender,"to",", ".join(receivers) 39 smtp.quit()
40 41
42 -class Server(smtpd.SMTPServer):
43 """ 44 Simple mail server. 45 46 Subclass mail.Server, providing the method process message and 47 start the service in a separate thread. 48 """
49 - def __init__(self, address='localhost:8025'):
50 if ':' in address: 51 host,port = address.split(':') 52 port = int(port) 53 else: 54 host,port = address,8025 55 print "serving from",host,port 56 smtpd.SMTPServer.__init__(self,(host,port),(host,port))
57
58 - def serve(self):
59 print "serving" 60 asyncore.loop() 61 print "done serving"
62
63 -def demo():
64 import thread 65 import time 66 import park.util.mail as mail 67 68 # Create the server and start it in a thread 69 class Server(mail.Server): 70 def process_message(self, peer, mailfrom, sendlist, msg): 71 print '>>>received msg' 72 print msg
73 74 server = Server(address='h123063.ncnr.nist.gov:25') 75 #server.serve() 76 thread.start_new_thread(server.serve, (())) 77 78 # Bounce a message off localhost:25 to the server. 79 sender = 'pkienzle@h123063.ncnr.nist.gov' 80 recvers = ['pkienzle@h123063.ncnr.nist.gov'] 81 msg = 'This is the transmitted message' 82 subject = 'to conditions' 83 #server='smtp.nist.gov:25' 84 #server='h123063.ncnr.nist.gov:8025' 85 mail.send(sender, recvers, msg, subject=subject, server=server) 86 time.sleep(10) 87 88 89 if __name__ == "__main__": 90 demo() 91