Mailcow: Reforward Messages

Modified on Wed, 1 Apr at 3:22 PM

#!/bin/bash

# --- CONFIGURATION ---
SOURCE_MAILBOX="mailcow@mydomain.com"
SEARCH_SUBJECT="You Got Tickets"
TARGET_EMAIL="remote@address.com"
LOOKBACK_TIME="12h"  # How far back to search (e.g., 1h, 12h, 1d, 2w)

# --- CONTAINER DETECTION ---
DOVECOT_ID=$(docker ps -qf name=dovecot-mailcow)
POSTFIX_ID=$(docker ps -qf name=postfix-mailcow)

# Check if containers are running
if [ -z "$DOVECOT_ID" ] || [ -z "$POSTFIX_ID" ]; then
    echo "Error: Could not find Mailcow containers. Are you in the mailcow directory?"
    exit 1
fi

# --- EXECUTION ---

echo "Searching for '$SEARCH_SUBJECT' in $SOURCE_MAILBOX within the last $LOOKBACK_TIME..."

# 1. Get the list of GUIDs and UIDs
RESULTS=$(docker exec $DOVECOT_ID doveadm search -u "$SOURCE_MAILBOX" subject "$SEARCH_SUBJECT" since "$LOOKBACK_TIME")

# Count results
COUNT=$(echo "$RESULTS" | grep -c '^' || echo 0)

if [ "$COUNT" -eq 0 ] || [ -z "$RESULTS" ]; then
    echo "No messages found."
    exit 0
fi

echo "Found $COUNT messages. Starting re-forwarding..."

# 2. Loop through the results
echo "$RESULTS" | while read -r guid uid; do
    if [ -z "$uid" ]; then continue; fi 
    
    echo " -> Resending UID: $uid..."
    
    # Fetch content and pipe to Postfix sendmail
    # -f ensures the envelope sender matches your domain to pass SPF
    docker exec $DOVECOT_ID doveadm fetch -u "$SOURCE_MAILBOX" text mailbox-guid "$guid" uid "$uid" | \
    docker exec -i $POSTFIX_ID sendmail -f "$SOURCE_MAILBOX" "$TARGET_EMAIL"
done

echo "Finished. Check the Postfix logs in the Mailcow UI to confirm delivery."

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article