function mail_encode($str, $eol = "\r\n")
{
// define start delimimter, end delimiter and spacer
$start = "=?UTF-8?B?";
$end = "?=";
$delimiter = "$eol ";
// Maximum length is 75. $split_length *must* be a multiple of 4, but <= 75 - strlen($start . $delimiter . $end)!!!
$split_length = 60;
$encoded_str = base64_encode($str);
// If encoded string meets the limits, we just return with the correct data.
if (strlen($encoded_str) <= $split_length)
{
return $start . $encoded_str . $end;
}
// If there is only ASCII data, we just return what we want, correctly splitting the lines.
if (strlen($str) === utf8_strlen($str))
{
return $start . implode($end . $delimiter . $start, str_split($encoded_str, $split_length)) . $end;
}
// UTF-8 data, compose encoded lines
$array = utf8_str_split($str);
$str = '';
while (sizeof($array))
{
$text = '';
while (sizeof($array) && intval((strlen($text . $array[0]) + 2) / 3) << 2 <= $split_length)
{
$text .= array_shift($array);
}
$str .= $start . base64_encode($text) . $end . $delimiter;
}
return substr($str, 0, -strlen($delimiter));
}