I need to be able to use my gmail from a php script. But whatever I try, the message body comes out all crappy with characters like =3D and random equals signs. Sometimes it comes out as base64 or nothing at alls. How can I fetch an email and dispay it in HTMLPurifier clean html or plain text in a pre if no html is available.
$overview = imap_fetch_overview($inbox,$email_number,0);
$body_pre = imap_fetchbody($inbox, $email_number, 2.1);
$message = imap_fetchbody($inbox, $email_number, 2.2);
$message = base64_decode($message);
if (empty($message))
{
$message = $body_pre;
$message = preg_replace('@(https?://([-\w\.]+)+(:\d+)?((/[\w/_\.%\-+~]*)?(\?\S+)?)?)@', '<a href="$1">$1</a>',$message);
$message = '<pre>'.htmlentities($message).'</pre>';
}else{
$cleanconfig = HTMLPurifier_Config::createDefault();
$cleanconfig->set('Core.Encoding', 'UTF-8');
$cleanconfig->set('HTML.Doctype', 'HTML 4.01 Transitional');
$purifier = new HTMLPurifier($cleanconfig);
$message = $purifier->purify($message);
}
this code, $message just comes blank.
You're assuming your mail message is always at position 2.2? There's absolutely no guarantees... depends on what message is sent you plan text (just one body), html/text (two), with attachment (three plus) in reply to another email (then the other email will be a body with it's own sub bodies).
The
=3D
(quoted printable) and base64 data are because of message body encodings. Have a look atimap_fetchstructure
which explains how many parts their are on a message (you can search through it to find text), and review the->type
component of each body to learn about it's encoding (type=4 is quoted printable, type=3 is base64)