I was using MIME::Lite in a Perl script recently, but ran across an issue. The issue is that I wanted to create a message that was multipart/alternative, so it would have a text friendly portion, an HTML portion, and (the part that caused my frustration) the HTML portion needed to be able to contain pictures within the HTML, not just added as attachments.
The problem was that every time I would attempt to craft such a message, the pictures I would attach wouldn't show up in the HTML. They would come across as attachments or not show up at all. The issue is because for the HTML to contain images, the HTML piece needs to be set as a type 'Multipart/Related', while the main message needs to be set as 'Multipart/Alternative'. Perhaps I just overlooked the obvious, but I never saw an example of how to do this. It gets pretty easy when you think of it logically though.
First, just create the main message like so ...
- my $msg = MIME::Lite::->new(
- 'To' => 'firstname.lastname@example.org',
- 'From' => 'email@example.com',
- 'Subject' => 'Hello',
- 'Type' => 'multipart/alternative',
Ok, now create the text part separately....
- my $text_part = MIME::Lite::->new(
- 'Type' => "text/plain",
- 'Data' => 'just a message',
Ok, now another part for the HTML, setting the type on this one to 'Multipart/Related'.
- my $html_part = MIME::Lite::->new(
- 'Type' => 'multipart/related',
Add the HTML you want. Include the picture. Then attach the picture to the HTML part.
- 'Type' => 'text/html',
- 'Data' => "<b>look at this picture!</b><br><img src=\"cid:picture.png\">",
- 'Type' => "image/png",
- 'Id' => "picture.png",
- 'Path' => "/path/to/picture.png",
Lastly, attach the text part to the main message, then attach the HTML part. This is actually the order in which mail clients prefer it.
There, now we have a message with text, html, and pictures in the html. You can then just send it off using MIME::Lite or you can output the message back as a string and send it via Net::SMTP , or whatever you prefer. I prefer Net::SMTP, so to get it as a string to send via that, just do ...
- my $email = $msg->as_string();
Hopefully this information may save someone lots of frustration =D