mail.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import sys
  2. import smtplib
  3. import warnings
  4. try:
  5. from email.mime.text import MIMEText
  6. except ImportError:
  7. from email.MIMEText import MIMEText
  8. supports_timeout = sys.version_info > (2, 5)
  9. class SendmailWarning(UserWarning):
  10. """Problem happened while sending the e-mail message."""
  11. class Message(object):
  12. def __init__(self, to=None, sender=None, subject=None, body=None,
  13. charset="us-ascii"):
  14. self.to = to
  15. self.sender = sender
  16. self.subject = subject
  17. self.body = body
  18. self.charset = charset
  19. if not isinstance(self.to, (list, tuple)):
  20. self.to = [self.to]
  21. def __str__(self):
  22. msg = MIMEText(self.body, "plain", self.charset)
  23. msg["Subject"] = self.subject
  24. msg["From"] = self.sender
  25. msg["To"] = ", ".join(self.to)
  26. return msg.as_string()
  27. class Mailer(object):
  28. def __init__(self, host="localhost", port=0, user=None, password=None,
  29. timeout=None):
  30. self.host = host
  31. self.port = port
  32. self.user = user
  33. self.password = password
  34. self.timeout = timeout
  35. def send(self, message):
  36. if supports_timeout:
  37. self._send(message, timeout=self.timeout)
  38. else:
  39. import socket
  40. old_timeout = socket.getdefaulttimeout()
  41. socket.setdefaulttimeout(self.timeout)
  42. try:
  43. self._send(message)
  44. finally:
  45. socket.setdefaulttimeout(old_timeout)
  46. def _send(self, message, **kwargs):
  47. client = smtplib.SMTP(self.host, self.port, **kwargs)
  48. if self.user and self.password:
  49. client.login(self.user, self.password)
  50. client.sendmail(message.sender, message.to, str(message))
  51. client.quit()
  52. def mail_admins(subject, message, fail_silently=False):
  53. """Send a message to the admins in conf.ADMINS."""
  54. from celery import conf
  55. if not conf.ADMINS:
  56. return
  57. to = [admin_email for _, admin_email in conf.ADMINS]
  58. message = Message(sender=conf.SERVER_EMAIL, to=to,
  59. subject=subject, body=message)
  60. try:
  61. mailer = Mailer(conf.EMAIL_HOST, conf.EMAIL_PORT,
  62. conf.EMAIL_HOST_USER,
  63. conf.EMAIL_HOST_PASSWORD,
  64. conf.EMAIL_TIMEOUT)
  65. mailer.send(message)
  66. except Exception, exc:
  67. if not fail_silently:
  68. raise
  69. warnings.warn(SendmailWarning(
  70. "Mail could not be sent: %r %r" % (
  71. exc, {"To": to, "Subject": subject})))