Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php imap - get body and make plain text

Tags:

php

email

mysql

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?

like image 915
user2710234 Avatar asked Sep 30 '13 10:09

user2710234


2 Answers

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)); 
like image 93
aleation Avatar answered Oct 13 '22 00:10

aleation


$data = imap_fetchbody($this->imapStream, $Part->uid, $Part->path, FT_UID | FT_PEEK);
if ($Part->format === 'quoted-printable' && $data) {
    $data = quoted_printable_decode($data);
}

This is required for mails with

Content-Transfer-Encoding: quoted-printable

But for mails with

Content-Transfer-Encoding: 8bit

simply imap_fetchbody is enough.

Above code was taken from a cake-php component created for fetching mails from mail boxes throgh IMAP.

like image 45
sumit Avatar answered Oct 13 '22 00:10

sumit