# -*- coding: utf-8 -*- from __future__ import absolute_import import subprocess from email.mime.text import MIMEText from email.utils import parseaddr from . import Backend class SendmailBackend(Backend): def send(self, recipient, subject, body, sender=None): if sender is None: sender = self.app.config['MAIL_DEFAULT_SENDER'] safe = lambda s: s.split('\n', 1)[0] msg = MIMEText(body, _charset='utf-8') msg['Subject'] = safe(subject) msg['To'] = safe(recipient) msg['From'] = safe(sender) envelope = [] _, address = parseaddr(safe(sender)) if address != '': envelope = ['-f', address] p = subprocess.Popen([self.app.config['SENDMAIL_COMMAND']] + envelope + ['-t'], stdin=subprocess.PIPE) p.stdin.write(msg.as_string()) p.stdin.close() if p.wait() != 0: raise RuntimeError('sendmail terminated with %d' % p.returncode)