From 28b442336218296ade8d2e98984f366945c8899c Mon Sep 17 00:00:00 2001 From: Nicholas Noll Date: Fri, 8 Oct 2021 16:33:40 -0700 Subject: feat(email): allowed for markdown inside emails --- bin/email | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100755 bin/email (limited to 'bin') diff --git a/bin/email b/bin/email new file mode 100755 index 0000000..231ab6c --- /dev/null +++ b/bin/email @@ -0,0 +1,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 + +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) -- cgit v1.2.1