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 = '[email protected]'
  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.