Saturday, November 21, 2009

UTF8 ready php mail function


I have been struggling for some time now to create a php mail function that can handle UTF8 characters across most email readers. I think I have finally accomplished this and it might be useful to others so here it is.


The problem with the php mail is that it does not encode the names and subjects and they could get lost in the transport or be misinterpreted from the email readers. This function actually does the proper encoding and overcomes the php mail deficiency.

—————————–
function UTF8_mail(
$from,$to,$subject,$message,$cc=”",$bcc=”"){


$from = explode(”<”,$from );


$headers =
“From: =?UTF-8?B?”
.base64_encode($from[0]).”?= <”
. $from[1] . “\r\n”;


$to = explode(”<”,$to );
$to = “=?UTF-8?B?”.base64_encode($to[0])
.”?= <”. $to[1] ;


$subject=”=?UTF-8?B?”
.base64_encode($subject).”?=\n”;


if($cc!=”"){
$cc = explode(”<”,$cc );
$headers .= “Cc: =?UTF-8?B?”
.base64_encode($cc[0]).”?= <”
. $cc[1] . “\r\n”;
}


if($bcc!=”"){
$bcc = explode(”<”,$bcc );
$headers .= “Bcc: =?UTF-8?B?”
.base64_encode($bcc[0]).”?= <”
. $bcc[1] . “\r\n”;
}


$headers .=
“Content-Type: text/plain; ”
. “charset=UTF-8; format=flowed\n”
. “MIME-Version: 1.0\n”
. “Content-Transfer-Encoding: 8bit\n”
. “X-Mailer: PHP\n”;


return mail($to, $subject, $message, $headers);


}


UTF8_mail(
“Γιω�?γος Κοντοπουλος <my@email.com>”,
“First Last <your@email.com>”,
“Θέμα Subject”,
“Κείμενο Text”,
“”,
“Κ�?υφός Φίλος<hidden_friend@email.com>”
);
—————————–


All this function is accomplishing is to encode each

Name<email@domain.com>

to

 =?UTF-8?B?zpzOuc+HzrHOu863z4I=?= <email@domain.com>

The emails themselves don’t need to be encoded since an email conventionally can only consist of of latin characters but, we could also confuse the mail server if we did encode them.


It has not been extensively tested, therefore I can’t guarantee that it would work with all possible mail readers. So please do send in your bug reports or any other comments.

No comments:

Post a Comment