Skip to content

Getting email recipient addresses from maildir

#! /bin/sh
#
# Get a directory name as input and grep the address the mail is sent to
#
# Based on a script by Joerg Reinhardt, but don't blame him for my mistakes

# Check for argument or help argument respectively
if [[ ($1 == "") ||
    ($1 == "-h") ||
    ($1 == "--help") ||
    ($1 == "-help") ]]; then
    echo "Usage: "$0" <Mail-directory> <Email-domain>";
fi;

# Make regex comparison case insensitive
shopt -s nocasematch

# Check if parameter is a directory
if [[ -d $1 ]]; then
# Set target filename
    dirname=`echo $1 | awk '{while(substr($0,length($0),1)=="/"){$0=substr($0,1,length($0)-1);}print $0;}'`;
    dumpfile=$dirname'.dump';

# Check if directory is empty
    if [[ `find $dirname -type f` == "" ]]; then
        echo $dirname": directory empty."
        exit 1;
    fi;

    regexDomain=$2+"$";

# Collect files inside maildir directories
    find $1 -regex '.*/cur/.*' -type f -print0 | while read -d $'\0' i; do
# Output progress information
        echo -n -e \\r"                                                                               "
        echo -n -e \\rprocessing "$i"
# Look for senders email address in the order
# 'To:'
# 'X-Original-To:'
# 'Delivered-To:'
        fromline=`grep '^To: ' "$i"`;
# Parse 'To:' field
        from=`echo $fromline | awk 'BEGIN{FS="<";}{if($0~/</) {pos=index($2,">");if(pos!=0) {print substr($2,1,pos-1);}} else {pos=index($0,":");print substr($0,pos+1);}}'`;
        if [[ $from == "" || ! $from =~ $regexDomain ]]; then
# Parse 'X-Original-To:' Field
            fromline=`grep '^X-Original-To: ' "$i"`;
            from=`echo $fromline | awk 'BEGIN{FS="Line:";}{print $2;}'`;
            if [[ $from == "" || ! $from =~ $regexDomain ]]; then
                fromline=`grep '^Delivered-To: ' "$i"`;
# Parse 'Delivered-To:' field
                from=`echo $fromline | awk 'BEGIN{FS="<";}{if($0~/</) {pos=index($2,">");if(pos!=0) {print substr($2,1,pos-1);}} else {pos=index($0,":");print substr($0,pos+1);}}'`;
                if [[ $from == "" || ! $from =~ $regexDomain ]]; then
# Looks like this email was not send to the user
                    continue;
                fi;
            fi;
        fi;

        echo $from | tr '[:upper:]' '[:lower:]' >> $dumpfile;
    done;
    echo;
else
    echo $1": not a directory.";
fi;

2 Comments

  1. /

    ./maildirparser: 8: Syntax error: word unexpected (expecting ")")

Trackbacks and Pingbacks

  1. Migrating a catch-all maildir to Office 365 | Michaël's coding thoughts

Leave a comment