Files
tomtomgames-app/mail_queue/process_queue.sh
T

44 lines
1.6 KiB
Bash

#!/bin/bash
# TomTomGames Mail Queue Processor
# Runs as root via cron every minute
# crontab entry: * * * * * /home/tomgames/public_html/../mail_queue/process_queue.sh >> /tmp/mailqueue.log 2>&1
QUEUE_DIR="$(dirname "$0")"
API_KEY=$(php -r "require '$(dirname "$0")/../includes/config.php'; echo SENDGRID_API_KEY;" 2>/dev/null)
if [ -z "$API_KEY" ]; then
# Fallback: read directly from config
API_KEY=$(grep "SENDGRID_API_KEY" "$(dirname "$0")/../includes/config.php" | grep -o "'SG\.[^']*'" | tr -d "'")
fi
for FILE in "$QUEUE_DIR"/*.json; do
[ -f "$FILE" ] || continue
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Processing: $FILE"
HTTP_CODE=$(curl -s -o /tmp/sg_response.txt -w "%{http_code}" \
--request POST \
--url https://api.sendgrid.com/v3/mail/send \
--header "Authorization: Bearer $API_KEY" \
--header "Content-Type: application/json" \
--data "@$FILE" \
--max-time 30)
if [ "$HTTP_CODE" = "202" ]; then
echo "[$(date '+%Y-%m-%d %H:%M:%S')] SUCCESS: $FILE (HTTP $HTTP_CODE)"
rm -f "$FILE"
else
RESPONSE=$(cat /tmp/sg_response.txt 2>/dev/null)
echo "[$(date '+%Y-%m-%d %H:%M:%S')] FAILED: $FILE (HTTP $HTTP_CODE) — $RESPONSE"
# Move to failed folder after 3 attempts
ATTEMPTS=$(cat "${FILE}.attempts" 2>/dev/null || echo 0)
ATTEMPTS=$((ATTEMPTS + 1))
echo $ATTEMPTS > "${FILE}.attempts"
if [ "$ATTEMPTS" -ge 3 ]; then
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Giving up after 3 attempts: $FILE"
mv "$FILE" "${FILE}.failed"
rm -f "${FILE}.attempts"
fi
fi
done