Using UTF-8 and Unicode data with Perl 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.

2 Responses to “Using UTF-8 and Unicode data with Perl MIME::Lite”

  1. Rob Perelman Says:

    Thanks for the tip! I ended up doing this instead for the second example:

    use Encode qw(encode);
    my $msg = MIME::Lite->new(

    Subject => encode(“MIME-B”, $subj),

    );

    Seems a lot simpler.

  2. Steve Says:

    THANK YOU! I have been trying to make my code work for ages ! Really thankful for stopping my white hear growing out :D

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

For inserting HTML or XML please remember to use &lt; instead of <