-1

Possible Duplicate:
PHP imap problems

I need to be able to use my mail (gmail) from a php script. But wherever I try, the email body comes out all rubbbish with characters like =3D and random equals signs. Sometimes it comes in as base64 or nothing at all. How can I get an email and display it in HTML Purifier clean html or plain text in a pre tag 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.

Community
  • 1
  • 1
  • what happens when you call imap_fetchbody() with 1 as last param ? – v0d1ch Jan 05 '13 at 12:27
  • With 1 I get the whole body of the mail with plain text and html with the content-type headers – user1948720 Jan 05 '13 at 12:47
  • Don't try to deal with email using PHP calls directly - mail is very hard to handle. Use a well-established library - there are a few for PHP. Maybe Swiftmailer will do this? http://swiftmailer.org/ – halfer Jan 05 '13 at 13:00
  • 1
    Also this: http://garrettstjohn.com/entry/reading-emails-with-php/ – halfer Jan 05 '13 at 13:04
  • thanks, but from what I can see swiftmailer is for mailing mails not getting them. – user1948720 Jan 05 '13 at 13:05
  • My problem is that I don't really know how to separate the message body and decode it as all the tutorials seem to skip over this bit – user1948720 Jan 05 '13 at 13:14

1 Answers1

1

The message with "characters like =3D and random equals signs" is quoted-printable encoded. You can decode using php with quoted_printable_decode.

There are different ways how mail messages can be encoded, like quited-printable or base64. The sender decides on the used encoding.

Niko Sams
  • 4,304
  • 3
  • 25
  • 44