Procmail Subject Rewrite – How to Rewrite Subject Line if Email Recipient User Fails Match Test

emailprocmailspam

I have a local procmail user "bob".

If an email arrives and matches [email protected], then no action should be taken.

However, if an email arrives and is [anything_else]@domain.com then I would like to rewrite the subject line to insert "[spam]" at the front of the subject line.

So it is a reverse match on "bob@" (match on anything other than bob@) and we preserve the original subject line, just prepending "[spam]" to the front of it.

How can I do that with Procmail?

Best Answer

Your requirements are rather unclear. Procmail can match on any string, but do you really mean to look for the string anywhere in the message? And do you really mean to ignore messages without domain.com in them for the purpose of this rule?

:0 HB
* ! ()\<bob@domain\.com\>
* @domain\.com\>
{
    :0fhw
    * ^Subject:\/.+
    | formail -I"Subject: [spam]$MATCH"
}

The \< and \> word boundaries prevent matching on substrings like tombob or subdomain.complete.org, and the empty parentheses are a hack because Procmail is weird about regexes which start with a backslash.

If you mean you want to look only in the headers, drop the HB from the first colon line (you could leave the H but that's the default if you don't put any flags). If you want to match a specific header, spell it out. If you want to examine the recipient specifically, the ^TO_ macro lets you do that in a number of different headers (To:, Cc:, etc) easily.

:0fhw
* ! ^TO_bob@domain\.com\>
* ^TO_[^<>@ ]+@domain\.com\>
* ^Subject:\/.+
| formail -I"Subject: [spam]$MATCH"

Because we dropped the HB flags, we can combine what was previously two recipes with different flags. The second ^TO_ checks for any address including bob, which however was already excluded by the previous negated condition.

This still has some corner cases which might need to be explored further; if you can edit your question to clarify it, perhaps I can update this to cover more than the basics.

SMTP doesn't require the recipient to be spelled out in the headers, though. The classic case is Bcc: which is also essentially the mechanism used by many mailing lists. Perhaps your MTA will spell out the recipient in Delivered-To: but properly speaking, this type of filter is better implemented in the MTA instead.