Skip to content

Instantly share code, notes, and snippets.

@jgeewax
Created December 7, 2015 17:59
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 12 You must be signed in to fork a gist
  • Save jgeewax/2c63810a534197c8a6be to your computer and use it in GitHub Desktop.
Save jgeewax/2c63810a534197c8a6be to your computer and use it in GitHub Desktop.
Script to configure Postfix for Mailgun
#!/bin/bash
# Configuration for the script
POSTFIX_CONFIG=/etc/postfix/main.cf
POSTFIX_SASL=/etc/postfix/sasl_passwd
function confirm () {
read -r -p "${1:-Are you sure? [Y/n]} " response
if [[ $response == "" || $response == "y" || $response == "Y" ]]; then
echo 0;
else
echo 1;
fi
}
# Check that we're root, otherwise exit!
if [ "$(id -u)" != "0" ]; then
echo "This script must be run as root!" 1>&2
exit 1
fi
# Read some configuration input
read -r -p "Enter your Mailgun SMTP login: " SMTP_LOGIN
read -r -p "Enter your Mailgun SMTP password: " SMTP_PASSWORD
CONTINUE=`confirm "Continue with $SMTP_LOGIN:$SMTP_PASSWORD? [Y/n] "`
if [[ CONTINUE -ne 0 ]]; then
echo "Aborting...";
exit;
fi
# Set a safe umask
umask 077
# Install postfix and friends
apt-get update && apt-get install postfix libsasl2-modules -y
# Comment out a couple transport configurations
sed -i.bak "s/default_transport = error/# default_transport = error/g" $POSTFIX_CONFIG
sed -i.bak "s/relay_transport = error/# relay_transport = error/g" $POSTFIX_CONFIG
sed -i.bak "s/relayhost =/# relayhost =/g" $POSTFIX_CONFIG
# Add the relay host for Mailgun, force SSL/TLS, and other config
cat >> $POSTFIX_CONFIG << EOF
# Mailgun configuration
relayhost = [smtp.mailgun.org]:2525
smtp_tls_security_level = encrypt
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
EOF
# Authentication stuff
cat > /etc/postfix/sasl_passwd << EOF
[smtp.mailgun.org]:2525 YOUR_SMTP_LOGIN:YOUR_SMTP_PASSWORD
EOF
# Generate a .db file and remove the old file
postmap $POSTFIX_SASL
rm $POSTFIX_SASL
# Set the permissions on the .db file
chmod 600 $POSTFIX_SASL.db
# Reload Postfix
/etc/init.d/postfix restart
@stevepop
Copy link

stevepop commented Jul 5, 2016

Thanks for sharing this. Quite helpful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment