aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorNicholas Noll <nbnoll@eml.cc>2021-10-08 16:33:40 -0700
committerNicholas Noll <nbnoll@eml.cc>2021-10-08 16:33:40 -0700
commit28b442336218296ade8d2e98984f366945c8899c (patch)
tree80ad17968cda29d3682c4f24dceb8256e6ad765f
parent8b679a2e892310e461c3f5028dfaf60b25eea37f (diff)
feat(email): allowed for markdown inside emails
-rwxr-xr-xbin/email75
1 files changed, 75 insertions, 0 deletions
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)