#!/usr/bin/env python3 """Feed email that exe.dev delivers to this VM into Chatwoot. exe.dev puts mail for *@.exe.xyz in ~/Maildir/new (https://exe.dev/docs/receive-email). This hands each message to Chatwoot's inbound email endpoint (Rails Action Mailbox, "relay" ingress), which turns it into a conversation in the Email inbox it was addressed to, then moves it to ~/Maildir/cur. A message Chatwoot refuses goes to ~/Maildir/failed. Standard library only. MAILDIR the Maildir (default /maildir) CHATWOOT_URL Chatwoot's internal address (default http://rails:3000) RAILS_INBOUND_EMAIL_PASSWORD the password Chatwoot expects for the relay """ import base64, os, sys, time, urllib.error, urllib.request MAILDIR = os.environ.get("MAILDIR", "/maildir") URL = os.environ.get("CHATWOOT_URL", "http://rails:3000").rstrip("/") + "/rails/action_mailbox/relay/inbound_emails" AUTH = "Basic " + base64.b64encode(b"actionmailbox:" + os.environ["RAILS_INBOUND_EMAIL_PASSWORD"].encode()).decode() def log(*args): print(*args, file=sys.stderr, flush=True) def post(raw): req = urllib.request.Request(URL, data=raw, method="POST", headers={"Content-Type": "message/rfc822", "Authorization": AUTH}) try: with urllib.request.urlopen(req, timeout=60) as r: return r.status except urllib.error.HTTPError as e: return e.code def main(): new, cur, failed = (os.path.join(MAILDIR, d) for d in ("new", "cur", "failed")) for d in (new, cur, failed): os.makedirs(d, exist_ok=True) log(f"mail-to-chatwoot: watching {new}, posting to {URL}") while True: for name in sorted(os.listdir(new)): path = os.path.join(new, name) try: with open(path, "rb") as f: raw = f.read() status = post(raw) except OSError as e: log(f"{name}: {e}; will retry") # Chatwoot is down or restarting continue if 200 <= status < 300: os.rename(path, os.path.join(cur, name + ":2,S")) log(f"{name}: delivered to Chatwoot") elif status >= 500 or status == 404: log(f"{name}: HTTP {status}; will retry") else: os.rename(path, os.path.join(failed, name)) log(f"{name}: HTTP {status}; moved to failed/") time.sleep(5) if __name__ == "__main__": main()