Skip to content

Instantly share code, notes, and snippets.

@kslimani
Last active August 29, 2015 14:21
Show Gist options
  • Save kslimani/f820575a8927c8d3572d to your computer and use it in GitHub Desktop.
Save kslimani/f820575a8927c8d3572d to your computer and use it in GitHub Desktop.
Bash script which watch Postfix virtual user mailbox folder
#!/bin/bash
#
# Watch Postfix virtual user mailbox folder.
#
# inotify-tools APT package is required
#
DEFAULT_USER="test"
DEFAULT_DOMAIN="yahoo.dev"
DEFAULT_MAILBOXES_DIR="/var/mail/virtual"
DEFAULT_DIR="new"
usage()
{
printf "Usage: ./watch.sh [USER] [DOMAIN] [cur|new|tmp] [MAILBOXES_FOLDER]\n\n"
exit 3
}
error()
{
echo "Error: $*"
exit 1
}
check_requirements()
{
reqcmd="awk date grep inotifywait sed"
for cmd in $reqcmd
do
if ! which $cmd &>/dev/null; then
error "$cmd command is required by this script"
fi
done
}
watch_mailbox()
{
user=$1
domain=$2
dir=$3
mboxesdir=$4
if [ -z "$user" ]; then
user=$DEFAULT_USER
fi
if [ -z "$domain" ]; then
domain=$DEFAULT_DOMAIN
fi
if [ -z "$dir" ]; then
dir=$DEFAULT_DIR
fi
if [ -z "$mboxesdir" ]; then
mboxesdir=$DEFAULT_MAILBOXES_DIR
fi
mbox_dir=$mboxesdir/$domain/$user/$dir
clear && show_messages $mbox_dir
inotifywait -q -m $mbox_dir -e create -e move -e delete |
while read path action file; do
# echo "The file '$file' appeared in directory '$path' via '$action'"
clear && show_messages $mbox_dir
done
}
show_messages()
{
msgs_dir=$1
if [ ! -d "$msgs_dir" ]; then
error "$msgs_dir folder not found"
fi
msgc=0
msgs=$(ls $msgs_dir)
for msg in $msgs
do
if show_message $msgs_dir/$msg; then
((msgc++))
fi
done
printf "\nFound $msgc message(s) in mailbox. Press CTRL+C to abort..."
}
show_message()
{
msg=$1
if [ -z "$1" ]; then
error "Message filename is missing"
fi
if [ ! -f "$1" ]; then
error "Message file not found"
fi
## Date: Fri, 15 May 2015 11:39:06 +0200
## From: postmaster@localhost
## To: [email protected]
## Subject: Welcome
msgdate=$(grep -m 1 '^Date: ' $msg|awk '{$1=""; print $0}'|sed 's/^ *//g')
msgfrom=$(grep -m 1 '^From: ' $msg|awk '{print $2}')
msgto=$(grep -m 1 '^To: ' $msg|awk '{print $2}')
msgsubject=$(grep -m 1 '^Subject: ' $msg|awk '{$1=""; print $0}'|sed 's/^ *//g')
shortdate=$(date -d "$msgdate" +%Y-%m-%d" "%H:%M:%S)
#echo "msgdate: $msgdate"
#echo "msgfrom: $msgfrom"
#echo "msgto: $msgto"
#echo "msgsubject: $msgsubject"
#echo "shortdate: $shortdate"
if [ -z "$msgdate" ]; then
## Parsing failed, maybe file is not a message ?
return 1
fi
echo "$shortdate $msgfrom $msgto $msgsubject" && return 0
}
## MAIN SCRIPT
if [ "$1" == "-h" ]; then
usage
fi
check_requirements
watch_mailbox $1 $2 $3 $4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment