Search code examples
procmail

Procmail to automatically make new folders to store emails from new senders


I am learning how to use procmail but at this point, I am not even sure it's the right tool for what I am trying to do.

So far, I have managed to get fetchmail to retrieve emails from a Google IMAP account and procmail to filter those emails into local folders I had previously created.

I am wondering though whether there is a way to get procmail to automatically create a new folder locally when an email from a new sender is being retrieved and to store that email into that folder.

So far, I have only found a website that describes the possibility of procmail creating automatically folders for mailing lists, but the recipe is something crazy using characters which I have no idea the meaning of, furthermore the official procmail website seems unreachable.

Please can you help? Thank you.


Solution

  • It's not clear what you expect the folder to be called, and what mailbox format you're using; but assuming maildir folders named by the sender's email terminus, try

    Who=`formail -rtzxTo:`
    :0
    * ? mkdir -p "$Who"
    $Who/
    

    For an mbox folder, you don't need the directory check at all, because the folder is just a single text file, and you'd drop the final slash from the folder name. Mbox needs locking, so add a second colon after the zero.

    Who=`formail -rtzxTo:`
    :0:
    $Who
    

    Getting formail to create a reply and then extracting the To: header of the generated reply is a standard but slightly unobvious way to obtain just the email terminus for the sender of the input message.

    The shell snippet mkdir -p dir creates dir if it doesn't already exist, and is a harmless no-op otherwise.