With a little side of applesauce...

Saturday, January 27, 2007

BASH fun - forwarding messages in Maildir

In my attempt to continue breaking the mail server, I had fixed the mailman router (exim4), but then email aliases began to deliver locally :( I fixed the problem, but then needed to deliver the (incorrectly) locally delivered message to the “real” email alias. BASH to the rescue:

for domain in $(ls /etc/mail/virtual/)
do
while read line
do
l=$(echo "$line" | grep -v localhost | cut -d: -f1)
r=$(echo "$line" | grep -v localhost | cut -d: -f2)
if [ "$l" != "" ] && [ "$r" != "" ] ; then
for f in $(ls /home/mail/$l/new/)
do
subject=$(cat /home/mail/$l/new/$f | grep "^Subject:")
echo "cat /home/mail/$l/new/$f | mail -s $subject $r"
cat /home/mail/$l/new/$f | mail -s "$subject" $r
unset subject
done
fi
done < /etc/mail/virtual/$domain
done

The domain files were kept in:

/etc/mail/virtual/mydomain.com

/etc/mail/virtual/anotherdomain.com

The files were in the format:

myemail: myemail@localhost

youremail: sam@gmail.com

And the new emails were in:

/home/mail/myuser/new (Maildir)

The script:

1. gets a listing of all available domains

2. cats the /etc/mail/virtual/domainfile into a while loop

3. sets l equal to the contents preceding the “:” (notice we ignore local users)
4. sets r equal to the contents after the “:” (notice we ignore local users)
5. loop through a list of files in /home/mail/$l/cur/

6. cat the file and grab the Subject: header

7. cat the file again into mail and set the subject to $subject

It isn’t perfect, (the sender is root@somesuch), but it at least gets them the mail, and they can still browse by subject…

No comments: