hacker has asked for the wisdom of the Perl Monks concerning the following question:

I've been working on a script that takes an incoming mail message (via Mail::Internet), parses out a template from the body of the message (via Config::General), executes on the key=value elements inside that template, runs a process that generates a few files (one binary file, one text file, one small html file), and sends them back to the user as attachments (via MIME::Lite) in either "raw" format (three files attached), or as one zip file containing the three attachments (via Archive::Zip). So far, this works beautifully.

What I'd like to do next, is allow the user to send the original mail with the template attached to the incoming message, rather than copied into the body of the message. I would then "detach" the template, parse it as before, and reply as normal. The problem I've run into is finding actual code that can deal with "detachments" in this fashion, where the incoming message is a stream, not written to a file on disk or into a mailbox.

I've Super Searched for anything related to "attachments" here, and found quite a few examples and code snippets, but almost all of them assume that the message resides inside a mailbox of mbox or maildir type. The incoming message is literally a stream of bytes, which I have to then splice up into header, body, and attachment. I did find MIME Attachment Extractor, which looked promising, but didn't seem to work with the incoming data I've got (never decoded it back to the original text file).

I've also looked at MIME::Decoder, MIME::Entity, MIME::Parser, and others, without much success. I can get the envelope and body, but for some reason, the attachment eludes me, or never decodes off in the right format (i.e. as a text file). It always seems to decode back to even worse binary junk than the raw attachment itself.

Has anyone done something similar to this, where the message is in a stream (not a mailbox) and successfully splice off the relevant parts of the incoming stream (envelope, body, attachment(s))? I'm looking for pointers to workable modules I may have overlooked, or small bits of code to point me in the right direction to banging this next feature out. Thanks again for any help, my fellow monks.