Saturday, September 13, 2008

MIME Trickery with MIME::Parser and friends

You can attach attachments to a multipart/related email message entity (say, a email message created from a website, with the images attached to the message itself) by creating a new multipart/mixed entity, and having the first part be that multipart/related entity and the rest being your new attachments. For example:

use strict;

use :MyMIMELiteHTML;
use MIME::Parser;
use MIME::Entity;

my $HTMLurl = 'http://localhost';
my $jpg_path = '/Users/justin/Desktop/4.jpg';

my $mailHTML = new MyMIMELiteHTML(
'IncludeType' => 'cid',

my $MIMELiteObj = $mailHTML->parse($HTMLurl) ;

my $msg_as_string = $MIMELiteObj->as_string;

my $parser = new MIME::Parser;

my $entity = $parser->parse_data($msg_as_string);

# Attach stuff to it:

my $cont_entity = MIME::Entity->build(Type => "multipart/mixed");
Path => $jpg_path,
Type => "image/jpg",
Encoding => "base64",
Disposition => "attachment",

print $cont_entity->stringify;

MyMIMELiteHTML is just my version of MIME::Lite::HTML, with a few bug fixes and changes to fit in my program better.

I've tried also just added the attachments to the multipart/related entity, but the new attachments never can be found - at least in (Gmail? Yes?), unless you put in a bogus Content-ID header for the attachement - which actually could come in handy in some rare cases, but I digress...

No comments: