mail.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import sys
  2. import smtplib
  3. try:
  4. from email.mime.text import MIMEText
  5. except ImportError:
  6. from email.MIMEText import MIMEText
  7. supports_timeout = sys.version_info >= (2, 6)
  8. class SendmailWarning(UserWarning):
  9. """Problem happened while sending the email message."""
  10. class Message(object):
  11. def __init__(self, to=None, sender=None, subject=None, body=None,
  12. charset="us-ascii"):
  13. self.to = to
  14. self.sender = sender
  15. self.subject = subject
  16. self.body = body
  17. self.charset = charset
  18. if not isinstance(self.to, (list, tuple)):
  19. self.to = [self.to]
  20. def __repr__(self):
  21. return "<Email: To:%r Subject:%r>" % (self.to, self.subject)
  22. def __str__(self):
  23. msg = MIMEText(self.body, "plain", self.charset)
  24. msg["Subject"] = self.subject
  25. msg["From"] = self.sender
  26. msg["To"] = ", ".join(self.to)
  27. return msg.as_string()
  28. class Mailer(object):
  29. def __init__(self, host="localhost", port=0, user=None, password=None,
  30. timeout=2):
  31. self.host = host
  32. self.port = port
  33. self.user = user
  34. self.password = password
  35. self.timeout = timeout
  36. def send(self, message):
  37. if supports_timeout:
  38. self._send(message, timeout=self.timeout)
  39. else:
  40. import socket
  41. old_timeout = socket.getdefaulttimeout()
  42. socket.setdefaulttimeout(self.timeout)
  43. try:
  44. self._send(message)
  45. finally:
  46. socket.setdefaulttimeout(old_timeout)
  47. def _send(self, message, **kwargs):
  48. client = smtplib.SMTP(self.host, self.port, **kwargs)
  49. if self.user and self.password:
  50. client.login(self.user, self.password)
  51. client.sendmail(message.sender, message.to, str(message))
  52. client.quit()