26a402e44eacd14b5d353e34623c9808016becdf
   1#
   2#   email.py
   3#
   4#   This module is essentially a wrapper for Python's premailer and whatever
   5#   the default mail handler is.
   6#
   7
   8import logging
   9logger = logging.getLogger(__name__)
  10
  11from os.path import isfile
  12import premailer
  13from email.mime.text import MIMEText
  14import subprocess
  15
  16def mailprep(htmlin, stylesheet):
  17    logger.debug("Converting stylesheet " + stylesheet + " to inline tags")
  18    if not isfile(stylesheet):
  19        logger.warning("Cannot read stylesheet {}: file does not exist".format(stylesheet))
  20        raise FileNotFoundError 
  21    pm = premailer.Premailer(htmlin, external_styles=stylesheet)
  22    htmlout = pm.transform()
  23    logger.info("Converted stylesheet to inline tags")
  24    return htmlout
  25
  26
  27def sendmail(mailbin, body, recipient, subject, html=True, sender=""):
  28    logger.debug("Sending email")
  29    msg = MIMEText(body, 'html' if html else 'plain')
  30    if sender:
  31        msg["From"] = sender
  32    msg["To"] = recipient
  33    msg["Content-type"] = "text/html: te: text/html" if html else "text/plain: te: text/plain"
  34    msg["Subject"] = subject
  35    mailproc = subprocess.Popen([mailbin, "--debug-level=" + str(10 if logging.root.level == logging.DEBUG else 0), "-t"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
  36    logger.debug("Compiled message and opened process")
  37    try:
  38        stdout = mailproc.communicate(msg.as_bytes(), timeout=15)
  39        logger.debug("sendmail output: {}".format(stdout))
  40        logger.info("Sent email to {0}".format(recipient))
  41        return 0
  42#    except TimeoutExpired:
  43#        mailproc.kill()
  44#        stdout = mailproc.communicate()
  45#        logger.debug("Timeout expired: {}".format(stdout))
  46#        raise subprocess.TimeoutError
  47    except Exception as e:
  48        mailproc.kill()
  49        logger.warning("Failed to send message: {0}".format(str(e)))
  50#        raise ChildProcessError