9e840a43fde9d92cbb848db0f6004d5b00340a2d
   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
  12from premailer import transform
  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, *sender):
  28    logger.debug("Sending email")
  29    msg = MIMEText(body)
  30    if sender:
  31        msg["From"] = sender
  32    msg["To"] = recipient
  33    msg["Subject"] = subject
  34    mailproc = subprocess.Popen([mailbin, '--debug-level=10', '-t'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
  35    logger.debug("Compiled message and opened process")
  36    try:
  37        stdout = mailproc.communicate(msg.as_bytes(), timeout=15)
  38        logger.debug("sendmail output: {}".format(stdout))
  39        logger.info("Sent email")
  40        return 0
  41#    except TimeoutExpired:
  42#        mailproc.kill()
  43#        stdout = mailproc.communicate()
  44#        logger.debug("Timeout expired: {}".format(stdout))
  45#        raise subprocess.TimeoutError
  46    except Exception as e:
  47        mailproc.kill()
  48        logger.warning("Failed to send message: {0}".format(str(e)))
  49#        raise ChildProcessError