diff options
author | Jameson Graef Rollins <jrollins@finestructure.net> | 2022-04-12 13:03:53 -0700 |
---|---|---|
committer | Sean Whitton <spwhitton@spwhitton.name> | 2022-05-16 16:45:24 -0700 |
commit | 932a5acda1c5e5fddcc4fba7d249b2d2b0168fa1 (patch) | |
tree | ffec91def4dc5a876c65237ffe1cd1e51f667dee /sendmail-reinject | |
parent | 6224a07059b71d279c424641422461810d273a6d (diff) | |
download | mailscripts-932a5acda1c5e5fddcc4fba7d249b2d2b0168fa1.tar.gz |
new script to reinject message via sendmail(1)
This script simply takes an existing mail file, parses it for sender
and all recipients, and constructs an appropriate sendmail(1) command
to resend the message.
It requires the sendmail(1) binary at runtime, and the notmuch python
library in order to extract the message from an existing notmuch
store.
Signed-off-by: Jameson Graef Rollins <jrollins@finestructure.net>
Diffstat (limited to 'sendmail-reinject')
-rwxr-xr-x | sendmail-reinject | 73 |
1 files changed, 73 insertions, 0 deletions
diff --git a/sendmail-reinject b/sendmail-reinject new file mode 100755 index 0000000..e50c484 --- /dev/null +++ b/sendmail-reinject @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 + +# SPDX-License-Identifier: GPL-2.0-or-later +# Copyright 2022 Jameson Graef Rollins + +import sys +import argparse +import subprocess + +import email +from email.policy import default +from email.utils import parseaddr, getaddresses + + +def sendmail(recipients, message, sender): + """send message via sendmail""" + cmd = [ + 'sendmail', + '-f', sender, + ] + recipients + print(' '.join(cmd), file=sys.stderr) + subprocess.run( + cmd, + input=message.as_bytes(), + check=True, + ) + + +def main(): + parser = argparse.ArgumentParser( + description="Reinject an email message via sendmail.", + ) + pgroup = parser.add_mutually_exclusive_group(required=True) + pgroup.add_argument( + 'message', nargs='?', type=argparse.FileType('rb'), + help="email message path or '-' for stdin", + ) + pgroup.add_argument( + '-i', '--notmuch-id', + help="message ID for notmuch extraction", + ) + + args = parser.parse_args() + + if args.id: + import notmuch2 as notmuch + db = notmuch.Database() + query = f'id:{args.id}' + assert db.count_messages(query) == 1, "Message ID does not match exactly one message??" + for msg in db.messages(query): + path = msg.path + break + f = open(path, 'rb') + else: + f = args.message + + # parse the email message + msg = email.message_from_binary_file(f, policy=default) + + sender = parseaddr(msg['from'])[1] + + # extract all recipients + tos = msg.get_all('to', []) + ccs = msg.get_all('cc', []) + resent_tos = msg.get_all('resent-to', []) + resent_ccs = msg.get_all('resent-cc', []) + recipients = [r[1] for r in getaddresses(tos + ccs + resent_tos + resent_ccs)] + + sendmail(recipients, msg, sender) + + +if __name__ == '__main__': + main() |