mime-mail

The safest way to add a header and a footer to an e-mail?


I am busy writing the last bit of an SMTP relay engine. Basically, people send mail to this SMTP address, it gets piped to files, analyzed, and then headers and footers are added to the body. My problem is, I'm not sure if my way of altering the mail will work for all cases. Basically, if I have this:

Return-path: <XXXX@YYYY>
Envelope-to: system-filter
Delivery-date: Thu, 25 Sep 2014 12:43:53 +0200
Received: from localhost ([127.0.0.1]:XXXX helo=XXXX.XXXX.com)
    by XXXX.XXXX.com with XXXX(XXXX-XXXX-XXXX-XXXX:XXXX)
    (Exim XXXX)
    (envelope-from <XXXX@XXXX.XXXX>)
    id XXXX-XXXX-67
    for XXXX.XXXX@XXXX.com; Thu, 25 Sep 2014 12:43:52 +0200
Received: from XXXX.XXXX.XXXX.XXXX ([197.87.204.210]) by XXXX.XXXX.com
 (Horde Framework) with HTTP; Thu, 25 Sep 2014 10:43:50 +0000
Date: Thu, 25 Sep 2014 10:43:50 +0000
Message-ID: <XXXX.Horde.XXXX@XXXX.XXXX.com>
From: XXXX@XXXX.XXXX
To: XXXX.XXXX@XXXX.com
Subject: This is the subject
User-Agent: Internet Messaging Program (IMP) H5 (XXXX)
Content-Type: text/plain; charset=UTF-8; format=flowed; DelSp=Yes
MIME-Version: 1.0
Content-Disposition: inline
X-OutGoing-Spam-Status: No, score=-2.9

And this is the message.

The idea was to either: 1. Just find the first blank line and put the header there, and then just append the footer to the end. 2. Use PHP Mime Mail Parser to alter the body

The problem with 1 is that I think there might be different formats coming in that don't follow the normal layout. The problem with 2 is, I'm limited to whatever the mail parser can parse.

So, what is the safest way to relay e-mails as I've desribed?


Solution

  • Just prepending or appending something to a message body will not work. It will not work because the message can by multipart (e.g. with attachments) or encoded (e.g. base64). PHP Mime Mail Parser seems to be able to handle these cases, but it doesn't have a method to save the modified message.

    I would recommend using some email parsing library which can write messages, not just read. For example, Python standard library has email package which can do what you need. However, you would have to check if the message is multipart and if so add the header and the footer to the right part (i.e. to the actual content and not to an image or attachment). You will also need to check whether the message is plain text or HTML and have your header and footer formatted appropriately.