user2710234 user2710234 - 1 month ago 24
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');


if($emails)
{
$output = '';

rsort($emails);

foreach($emails as $email_number)
{
$header=imap_headerinfo($inbox,$email_number);

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

//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
=20
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?

Answer

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.

Basically:

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