user2710234 user2710234 - 2 months ago 42
MySQL Question

php imap - get body and make plain text

I am using the PHP imap function to get emails from a POP3 mailbox and insert the data into a MySQL database.

Here is the PHP code:

$inbox = imap_open($hostname,$username,$password) or die('Cannot connect: ' . imap_last_error());

$emails = imap_search($inbox,'ALL');

$output = '';


foreach($emails as $email_number)

$from = $header->from[0]->mailbox . "@" . $header->from[0]->host;
$datetime=date("Y-m-d H:i:s",$header->udate);

//remove the " from the $toaddress
$toaddress = str_replace('"','',$toaddress);

echo '<strong>To:</strong> '.$toaddress.'<br>';
echo '<strong>From:</strong> '.$from.'<br>';
echo '<strong>Subject:</strong> '.$subject.'<br>';

//get message body
$message = (imap_fetchbody($inbox,$email_number,1.1));
if($message == '')
$message = (imap_fetchbody($inbox,$email_number,1));

It works fine, however on some emails in the body I get
in between words, or
in between words. And other times the emails will just be blank even though they are not blank when sent.

This only happens when coming from certain emails.

How can I get round this and just make the email completely plain text?


This happens because the emails are normally Quoted-printable encoded. The = is a soft line break and =20 is a white space. I think, you could use quoted_printable_decode() on the message so it shows correctly. About the blank emails, I don't know, I would need more details.


//get message body
$message = quoted_printable_decode(imap_fetchbody($inbox,$email_number,1.1));