Skip to content

Instantly share code, notes, and snippets.

@thehunmonkgroup
Last active October 17, 2022 11:48
Show Gist options
  • Save thehunmonkgroup/249d599f81380bf0efc8 to your computer and use it in GitHub Desktop.
Save thehunmonkgroup/249d599f81380bf0efc8 to your computer and use it in GitHub Desktop.
Resend Postfix messages stuck in mail queue to another address
#!/bin/bash
# This script allows sending of messages stuck in the Postfix queue to another
# email address. Useful if the original email address is bad.
if [ $# -ne 2 ]; then
echo "Usage: reroute-queued-email-messages.sh <oldaddress> <newaddress>"
exit 1
fi
OLD_ADDRESS="$1"
NEW_ADDRESS="$2"
MAILQ=`which mailq`
POSTCAT=`which postcat`
POSTSUPER=`which postsuper`
SENDMAIL=`which sendmail`
TAIL=`which tail`
GREP=`which grep`
AWK=`which awk`
SED=`which sed`
# Pulls queue IDs for all messages sent to the original address.
function get_ids_by_address {
$MAILQ | $TAIL -n +2 | $GREP -v '^ *(' | $AWK -v address="$1" 'BEGIN { RS = "" } { if ($8 == address) print $1 }'
}
MESSAGE_IDS=`get_ids_by_address $OLD_ADDRESS`
# Loop through each message ID, output the message, and pipe it through
# sendmail to the new address.
for message_id in $MESSAGE_IDS;
do
# Puts the message on hold.
$POSTSUPER -h $message_id
# Extract the sender.
sender=`$POSTCAT -q $message_id | $GREP -m 1 '^From: ' | $SED '/^From: */!d; s///; q'`
# sed gets rid of the leading queue metadata, grep -v gets rid of the
# metadata markers.
$POSTCAT -q $message_id | $SED -n '/MESSAGE CONTENTS/,$p' | $GREP -v "^\*\*\*.*\*\*\*$" | sendmail -f "$sender" $NEW_ADDRESS
echo "Delivered message ID $message_id to $NEW_ADDRESS"
done
echo -n "Remove old messages from mail queue? [y/N]: "
read delete
if [ "$delete" = "y" ]; then
for message_id in $MESSAGE_IDS;
do
# Deletes the message from the mail queue by queue ID.
$POSTSUPER -d $message_id
echo "Deleted message ID $message_id from queue"
done
else
for message_id in $MESSAGE_IDS;
do
# Takes the message off hold.
$POSTSUPER -H $message_id
done
echo "The following messages were left in the mail queue:"
echo "$MESSAGE_IDS"
fi
exit 0
@schose
Copy link

schose commented Aug 22, 2018

perfekt! you saved my emails and life!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment