summaryrefslogtreecommitdiffstats
path: root/accounts/backend/mail/sendmail.py
blob: 1fecedc4d801d420fb0507d74685ee708523f818 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# -*- coding: utf-8 -*-


import subprocess
from email.mime.text import MIMEText
from email.utils import parseaddr
from jinja2.environment import TemplateModule

from . import Backend


def safe(s: str):
    return s.split('\n', 1)[0]


class SendmailBackend(Backend):
    def _send(self, recipient: str, content: TemplateModule):
        msg = MIMEText(content.body(), _charset='utf-8')  # type: ignore
        msg['Subject'] = safe(content.subject())  # type: ignore
        msg['To'] = safe(recipient)
        msg['From'] = safe(content.sender())  # type: ignore

        envelope = []
        _, address = parseaddr(safe(content.sender()))  # type: ignore
        if address != '':
            envelope = ['-f', address]

        p = subprocess.Popen([self.app.config['SENDMAIL_COMMAND']] +
                             envelope + ['-t'], stdin=subprocess.PIPE)
        assert p.stdin
        p.stdin.write(msg.as_string().encode("utf-8"))
        p.stdin.close()

        if p.wait() != 0:
            raise RuntimeError('sendmail terminated with %d' % p.returncode)