emailutils.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014, 2015 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """ This module allows you to send out emails.
  16. """
  17. import email.utils
  18. import smtplib
  19. import twisted.python.log
  20. from email.mime.text import MIMEText
  21. from email.mime.multipart import MIMEMultipart
  22. import logging
  23. logger = logging.getLogger(__name__)
  24. class EmailException(Exception):
  25. pass
  26. def send_email(smtp_server, from_addr, to_addr, subject, body):
  27. """Sends an email.
  28. Args:
  29. smtp_server(str): The SMTP server to use.
  30. from_addr(str): The address to send from.
  31. to_addr(str): The address to send to.
  32. subject(str): The subject of the email.
  33. body(str): The plain text body of the email.
  34. Raises:
  35. EmailException if there was a problem sending the mail.
  36. """
  37. if not smtp_server or not from_addr or not to_addr:
  38. raise EmailException("Need SMTP server, from and to addresses. Check"
  39. " the config to set these.")
  40. msg = MIMEMultipart('alternative')
  41. msg['Subject'] = subject
  42. msg['From'] = from_addr
  43. msg['To'] = to_addr
  44. plain_part = MIMEText(body)
  45. msg.attach(plain_part)
  46. raw_from = email.utils.parseaddr(from_addr)[1]
  47. raw_to = email.utils.parseaddr(to_addr)[1]
  48. if not raw_from or not raw_to:
  49. raise EmailException("Couldn't parse from/to address.")
  50. logger.info("Sending email to %s on server %s with subject %s",
  51. to_addr, smtp_server, subject)
  52. try:
  53. smtp = smtplib.SMTP(smtp_server)
  54. smtp.sendmail(raw_from, raw_to, msg.as_string())
  55. smtp.quit()
  56. except Exception as origException:
  57. twisted.python.log.err()
  58. ese = EmailException()
  59. ese.cause = origException
  60. raise ese