Wednesday, September 30, 2009

Different SMTP relay host depending on the location

Okay, after thinking about the problem and brainstorming a bit, I came up with a solution for my "smtp from two locations" problem. The solution is tied to NetworkManager and is actually pretty straightforward (if a bit kludgy).

This is what I wrote and placed in /etc/NetworkManager/dispatcher.d/10-relayhost, and it expects to have a default installation of postfix, with at least one uncommented relayhost= line (doesn't matter what's in the line itself). By default, postfix listens on localhost:25, which is fine for me. I have configured claws-mail to always use localhost:25 as the SMTP server, and it's working just fine, automatically switching my relayhost from mcgill's to my ISP's depending on where I am at the moment. It can probably be improved further, but this is the general idea.

Of course, a better solution would be to have mailhost.mcgill.ca accept mail relaying for authenticated connections, but that's a bit of a pie in the sky at the moment.

Hope this helps someone with a similar problem.
#!/bin/sh

CONF="/etc/postfix/main.cf"
HOME="smtp.teksavvy.ca"
WORK="mailhost.mcgill.ca"

if [ "$2" = "up" ]; then
if `/sbin/ifconfig | grep -q 'inet addr:192.168.1.'`; then
# we're at home
sed -i -e "s/^relayhost=.*/relayhost=${HOME}/g" ${CONF}
elif `/sbin/ifconfig | grep -q 'inet addr:132.2'`; then
# we're at work
sed -i -e "s/^relayhost=.*/relayhost=${WORK}/g" ${CONF}
else
# we're elsewhere, unset relayhost and hope for the best
sed -i -e "s/^relayhost=.*/relayhost=/g" ${CONF}
fi
/sbin/service postfix reload
fi

2 comments:

Rob said...

Cool!

BTW, you can remove all the backquotes. Command substitution is not necessary in those cases.

michaelarnold said...

Why not use "postconf -e 'relayhost = wherever' instead of sed?