From 79c4ba81fcdaa1c19ef245a657ec2cbf4776c76c Mon Sep 17 00:00:00 2001 From: Brian Read Date: Fri, 13 Jun 2025 09:23:24 +0100 Subject: [PATCH] Add possible script to notify for postfix --- postfix_notify.sh | 61 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 postfix_notify.sh diff --git a/postfix_notify.sh b/postfix_notify.sh new file mode 100644 index 0000000..5407233 --- /dev/null +++ b/postfix_notify.sh @@ -0,0 +1,61 @@ +#!/bin/bash +# postfix-delay-notify.sh +# Custom delayed mail notifier for Postfix + +# Configuration +DELAY_WARNING_HOURS=4 # Match delay_warning_time in main.cf +TEMPLATE_FILE="/etc/postfix/delay_template.txt" +LOCK_FILE="/tmp/postfix-delay-notify.lock" +LOG_FILE="/var/log/postfix-delay-notify.log" + +# Create lock file or exit if already running +exec 9>"$LOCK_FILE" || exit 1 +flock -n 9 || exit 1 + +# Function to log messages +log() { + echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> "$LOG_FILE" +} + +# Check template file exists +[[ -f "$TEMPLATE_FILE" ]] || { + log "Error: Template file $TEMPLATE_FILE not found" + exit 1 +} + +# Process mail queue +postqueue -p | awk ' +BEGIN { OFS="|"; FS="[ *]" } +/^[A-F0-9]{10}\!/ { + qid=$1 + sender=$(NF-1) + recipient=$NF + time=$3" "$4 + print qid, sender, recipient, time +}' | while IFS='|' read -r qid sender recipient queue_time; do + + # Calculate time in queue (hours) + queue_seconds=$(( $(date +%s) - $(date -d "$queue_time" +%s) )) + queue_hours=$(( queue_seconds / 3600 )) + + if [[ $queue_hours -ge $DELAY_WARNING_HOURS ]]; then + # Generate notification using template + notification=$(sed -e "s/%HOSTNAME%/$(hostname)/g" \ + -e "s/%DELAY%/$queue_hours hours/g" \ + -e "s/%LIFETIME%/72 hours/g" \ + "$TEMPLATE_FILE") + + # Send notification + echo "From: postmaster@$(hostname) +To: $sender +Subject: Delivery Delay Notification +Content-Type: text/plain; charset=utf-8 + +$notification" | sendmail -t -oi + + log "Sent delay notification for QID $qid to $sender" + fi +done + +# Cleanup +rm -f "$LOCK_FILE" \ No newline at end of file