Sunday, December 9, 2012

How to properly encode email subject

When we want to send a email with non US characters in email subject it is important to properly encode it. Below is the most simple code that does just that (thanks Gasper for help).
<?php
public function email_subject_encode($in_str, $charset = 'UTF-8') {

    #remove all non utf8 characters
    $in_str = mb_convert_encoding($in_str, $charset, $charset);

    #Remove non printable character (i.e. below ascii code 32).
    $in_str = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F]/u',
                           '', $in_str);

    #encode email subject
    $out_str ="=?utf-8?b?".base64_encode($in_str)."?=";

    return $out_str;
  }
?>
Post a Comment