HTML Email with Text Plain Backup. Notes for MIME::Lite and PHP Pear

Recently I’ve been working on some code that needed to have HTML email sent along with plain text email.  One application was the “email a photo” option for  The other option, and the one where it wasn’t working right, was for, basically a trucking logistics company.  The trucking industry isn’t the most high tech, and there are still people out there using email clients that don’t support HTML.

Anyway, here we go.

With PHP Pear, the code is smart enough to figure things out itself.  However, with MIME::Lite, you have to build the message yourself.

The answer to the problem is to use the “Multipart/Alternative” as your mime type, put the text/plain part first (for AOL support), and don’t attach the HTML as a file (attach it as data).


my $mime_msg = MIME::Lite->new(
    From => “”,
    To   => $email,
    Subject => ‘multipart/alternative’,
    Type => $mime_type,
) or die “Error creating MIME body: $!\n”;

$mime_msg->attach(Type => ‘text/plain’,
    Data => qq{ Your Message Body });

$mime_msg->attach(Type => ‘text/html’,
    Data => qq{ Your HTML Message Body });

However, I had a problem.  I was calling various scripts to build a big HTML file, which would then be attached, so i was doing:

$mime_msg->attach(Type => ‘text/html’,
    File => $html_file_path);

Don’t do that.  Instead, read the file into an array, then join the array into a string.  I dont know why, but some mail readers (including gmail) saw that the HTML attached was a file, and treated it as an attachment, rather than an alternative way of presenting the same message.

Hope this helps you!  If you have anything to add, reply!

Published by


I'm a software engineer in New Orleans interested in making things, growing things, big fast computers, media convergence, and pugs.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>