Postfix Mail Queue Monitor Shell Script for Linux Servers

postfix mail queue monitor script

Monitor your Postfix mail queue with a Bash script — detect backlog, stuck messages, and mail server issues before users complain.

What this script does

  • Reports current Postfix queue size
  • Alerts when queue exceeds configurable threshold
  • Lists oldest messages in queue
  • Optional flush of deferred queue
  • Logs results for cron monitoring

Prerequisites

  • Postfix installed
  • mailq/postqueue commands available
  • Root or postfix group access

Step 1: Save the script

sudo nano /usr/local/bin/postfix-queue-monitor.sh
sudo chmod +x /usr/local/bin/postfix-queue-monitor.sh

Step 2: Full script (scroll to read)

postfix-queue-monitor.sh
#!/usr/bin/env bash
set -euo pipefail

MAX_QUEUE=50
ALERT_EMAIL="[email protected]"
FLUSH_DEFERRED=false
LOG="/var/log/postfix-queue.log"

log(){ echo "[$(date '+%F %T')] $*" | tee -a "$LOG"; }

QUEUE=$(mailq | tail -n1 | awk '{print $5}' | tr -d '!' || echo 0)
QUEUE=${QUEUE:-0}
log "Postfix queue size: $QUEUE messages"

if (( QUEUE > MAX_QUEUE )); then
  log "WARNING: Queue exceeds threshold ($MAX_QUEUE)"
  mailq | head -20 | tee -a "$LOG"
  if $FLUSH_DEFERRED; then
    log "Flushing deferred queue..."
    postqueue -f
  fi
  [[ -n "$ALERT_EMAIL" ]] && command -v mail >/dev/null && \
    echo "Postfix queue has $QUEUE messages on $(hostname -s)" | \
    mail -s "Postfix queue alert" "$ALERT_EMAIL"
  exit 1
fi
log "Queue OK"
exit 0

Scroll inside the box to read the full script.

Step 3: Configure settings

  • MAX_QUEUE — alert when messages exceed this count
  • ALERT_EMAIL — admin notification
  • FLUSH_DEFERRED — true to run postqueue -f
Postfix mail queue monitor shell script on Linux
Postfix mail queue monitor shell script on Linux

Step 4: Test manually

sudo /usr/local/bin/postfix-queue-monitor.sh
mailq | head

Schedule with cron

sudo crontab -e

Add:

*/30 * * * * /usr/local/bin/postfix-queue-monitor.sh >> /var/log/postfix-queue.log 2>&1

Related tutorials

Terminal screenshot is an original illustration created for Gnome IT Solutions (blog.gnomeitsolutions.com).