mysociety/alaveteli

View on GitHub
script/mailin

Summary

Maintainability
Test Coverage
#!/bin/bash

export RUBYOPT="-W0"

# Wire this script to receive incoming email for request responses.

INPUT=$(mktemp -t foi-mailin-mail-XXXXXXXX)
OUTPUT=$(mktemp -t foi-mailin-output-XXXXXXXX)

# Read the email message from stdin, and write it to the file $INPUT
cat >"$INPUT"

cd "$(dirname "${BASH_SOURCE[0]}")"/..

bundle exec rails runner 'RequestMailer.receive(STDIN.read)' <"$INPUT" >"$OUTPUT" 2>&1
ERROR_CODE=$?
if [ ! "$ERROR_CODE" = "0" ]
then
    # we should never get an error here, unless the database is down or similar

    # send error to administators (use mutt for MIME encoding)
    SUBJ="Mail import error for $(bin/config DOMAIN)"
    BODY="There was an error code $ERROR_CODE returned by the RequestMailer.receive command in script/mailin. See attached for details. This might be quite serious, such as the database was down, or might be an email with corrupt headers that Rails is choking on. We returned the email with an exit code 75, which for Exim at least instructs the MTA to try again later. A well configured installation of this code will separately have had Exim make a backup copy of the email in a separate mailbox, just in case."
    FROM="$(bin/config BLACKHOLE_PREFIX)@$(bin/config INCOMING_EMAIL_DOMAIN)"
    /usr/bin/mutt -e "set use_envelope_from" -e "set envelope_from_address=$FROM" -s "$SUBJ" -a "$OUTPUT" "$INPUT" -- "$(bin/config EXCEPTION_NOTIFICATIONS_TO)" <<<"$BODY"

    # tell exim error was temporary, so try again later (no point bouncing message to authority)
    rm -f "$INPUT" "$OUTPUT"
    exit 75
fi

cat "$OUTPUT"
rm -f "$INPUT" "$OUTPUT"
exit 0