Saturday, April 18, 2009

Unicode utf-8 in Mysql,perl DBI,MIME::Lite

I have a database which stores unicode text. Periodically I need to get the stored text and mail to a mailing list. Initially the text received through the mail was unreadable. After several tries and spending sometime multiple documentation pages, I found all the right settings.

For the mysql DBI you have specifically enable utf8 processing of the strings. There are other ways to achieve this like converting each string. But it will quickly become tedious. This is the easiest.


use DBI;
my $dbh = DBI->connect("DBI:mysql:${database}:${hostname}", $username, $password)
or die "DB Connection not made: $DBI::errstr";
$dbh->{'mysql_enable_utf8'} = 1;
$dbh->do('SET NAMES utf8');


For sending the mail, you tell MIME::Lite the charset(utf8) and encoding(8bit).


my $msg = MIME::Lite->build(
From => 'user@sample.com',
To => $recipient_emailid,
Subject => "=?UTF-8?B?" .
encode("utf-8", $subject) ."?=",
Type => 'TEXT',
Encoding=> '8bit',
Charset => 'utf-8',
Data => $body
);
$msg->attr("content-type.charset" => "utf-8");

$msg->send;

No comments: