Using UTF-8 and Unicode data with Perl’s MIME::Lite

MIME::Lite predates Perl 5.8 which supports Unicode and UTF-8. But it's easy to get MIME::Lite to work with Unicode bodies and subjects.

To attach a plain text part to a message, with a string which contains unicode characters, use:

$msg->attach(
   Type => 'text/plain; charset=UTF-8',
   Data => encode("utf8", $utf8string),
);

To set the subject of a mail from a string containing unicode characters, use:

use MIME::Base64;
my $msg = MIME::Lite->new(
   ...
   Subject =>   "=?UTF-8?B?" .
      encode_base64(encode("utf8", $subj), "") . "?=",
   ...
);

Note that the above methods also work even if the strings do not contain unicode characters, or do not have the UTF-8 bit set.

It would be better to change MIME::Lite such that subject and data strings are accepted and the above code happens inside MIME::Lite. I've filed a bug report. It was rejected.

P.S. I recently created a nerdy privacy-respecting tool called When Will I Run Out Of Money? It's available for free if you want to check it out.

This article is © Adrian Smith.
It was originally published on 27 Feb 2007
More on: Perl