Procmail – Replace From with text from within email

pipeprocmailsed

I am trying to use Procmail to filter through mail that goes to my ticket channel in WHMCS. It works fine as far as piping goes. But emails from the Zopim live chat module on the site need filtering and editing before they go to the script for WHMCS.

The emails as they come in are like so:

To: email@domain.com
From: Zopim <noreply@zopim.com>
Subject: Offline Message from Visitor xxxx: xxx

From: Visitor xxxxxx <you@you.com>

URL: http://www.domain.com

xxxxxxx

----
Zopim
http://www.zopim.com

And here is my procmail rc file setup:

:0H
* ^From: Zopim.*noreply@zopim.com
| sed -e 's/^From: Zopim.*/From: me@me\.com/' | /usr/bin/php -q /var/www/pipe/pipe.php

Now, that is working fine, it's finding the From field and replacing it with me@me.com. The problem is I want to somehow get the text from inside the email where it says:

From: Visitor xxxxxx <you@you.com>

And put that above in the header where From is at, so in essence it will be coming from the visitor and not zopim. This is where my problem lies, I can't figure out using sed or another program how to set that line as a Variable and replace it above, or just using sed to move lines around.

Best Answer

Assuming these emails are really regular, so that the first From: in the body always contains the address you want to extract, try something like this:

:0  # The H flag is the default, so not specifying it explicitly
* ^From: Zopim.*<noreply@zopim\.com>
{
    :0B # examine body only, capture From:
    * ^From: \/[^ ].*$
    { VISITOR=$MATCH }

    :0
    | formail -I "From: $VISITOR" \
      | /usr/bin/php -q /var/www/pipe/pipe.php
}

Traditionally, the regex should cover tabs as well as spaces in the whitespace, but I imagine if your input is machine generated, it will be all spaces (or all tabs, in which case you'll need to make the necessary edits).