We Recommend

Learning Python Learning Python
The authors of Learning Python show you enough essentials of the Python scripting language to enable you to begin solving problems right away, then reveal more powerful aspects of the language one at a time. This approach is sure to appeal to programmers and system administrators who have urgent problems and a preference for learning by semi-guided experimentation.


Posted By

kangell on 04/07/08


Tagged

email message send e-mail


Versions (?)


Who likes this?

2 people have marked this snippet as a favorite

sudarkoff
pulczynski


Send An Email Message


Published in: Python 


Send an e-mail message to the given addresses.

  1. from smtplib import SMTP
  2. DEF_FROM = 'me@example.com'
  3. DEF_SMTP_SERVER = 'localhost'
  4.  
  5. class SENDMAILError:
  6.  
  7. def __init__( self, error ):
  8. self.error = error
  9.  
  10. def __repr__( self ):
  11. return self.error
  12.  
  13. def sendmail( toaddrs, msg, subject=None, fromaddr=DEF_FROM, smtpServer=DEF_SMTP_SERVER ):
  14. """Send an email to the given addresses"""
  15.  
  16. if smtpServer is None:
  17. smtpServer = 'localhost'
  18.  
  19. if type( toaddrs ) is StringType:
  20. toaddrs = toaddrs.split()
  21. elif not type( toaddrs ) is ListType:
  22. raise SENDMAILError( "toaddrs must be a string or a list" )
  23.  
  24. try:
  25. headers = ("From: %s\nTo: %s\n\n"
  26. % ( fromaddr, ", ".join( toaddrs ) ) )
  27. if not subject is None:
  28. headers = "Subject: %s\n" % subject + headers
  29.  
  30. server = SMTP( smtpServer )
  31. server.sendmail( fromaddr, toaddrs, headers + msg )
  32. server.quit()
  33. except Exception, e:
  34. raise SENDMAILError( str( e ) )

Report this snippet 

You need to login to post a comment.