aboutsummaryrefslogtreecommitdiff
path: root/bin/email
blob: efe390696a2a58a7246cbeaaef2862d2a1962f7b (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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/python

import sys,re
import email

from email import policy
from subprocess import run, PIPE

mstmp = "/usr/bin/msmtp"

def log(*args):
    print(*args, file=sys.stderr)

def html(markdown):
    cmd = run(["pandoc", "-s", "--metadata", "title=", "-f", "markdown", "-t", "html"], input=markdown, stdout=PIPE, encoding='utf-8')
    if cmd.returncode != 0:
        return None

    return cmd.stdout

startbang =  r"\A\s*^[ \t]*!md[ \t]*$"
stopbang  =  r"^[ \t]*!md[ \t]*$"
def trim(content):
    clean, n1 = re.subn(startbang, "", content, flags=re.MULTILINE | re.DOTALL)
    clean, n2 = re.subn(stopbang,  "", clean, flags=re.MULTILINE | re.DOTALL)

    if n1 == 1 and n2 == 1:
        return clean
    return None

def process(mail):
    changed = False
    for part in mail.walk():
        if part.get_content_maintype() == "text" and part.get_content_charset() == "utf-8":
            content  = part.get_content()
            markdown = trim(content)
            if markdown is None:
                continue
            else:
                part.set_content(markdown)
                part.add_alternative(html(markdown), subtype="html")
                changed = True
        else:
            continue

    return changed

def mail(input):
    message = email.message_from_string(input, policy=policy.default)

    if process(message):
        return message.as_bytes()

    return input.encode("utf-8")

def send(account, to):
    input = sys.stdin.read()
    email = mail(input)

    cmd = run([mstmp, "-a", account, "--", to], input=email)
    if cmd.returncode != 0:
        raise ValueError(f"did not send mail. err={cmd.returncode}")

if __name__ == "__main__":
    if len(sys.argv) != 4:
        raise ArgumentError(f"invalid usage: recieved arguments {sys.argv[1:]}")

    account = sys.argv[1]

    if sys.argv[2] != "--":
        raise ArgumentError(f"invalid usage: received {sys.argv[2:]} instead of recipient")

    to = sys.argv[3]

    send(account, to)