Question

I'm trying to write a script which downloads all mail in a certain folder without a custom flag, let's call the flag $aNiceFlag for now; after I've fetched a mail I want to flag it with $aNiceFlag. However before tackling the flag problem I've got a problem to extract the content i need from the mail right now.

This is the information I need:

  • Sender (email and name if possible)
  • Subject
  • Receiver
  • Plain text body (if only html is available I will try convert it from html to plaintext)
  • Time sent

I can easily get the subject by using $mailObject->subject. I'm looking at the Zend Documentation but it's a bit confusing for me.

Here's my code right now, I'm not supposed to echo out the content but that's just for now while testing:

$this->gOauth = new GoogleOauth();
$this->gOauth->connect_imap();
$storage = new Zend_Mail_Storage_Imap(&$this->gOauth->gImap);
$storage->selectFolder($this->label);
foreach($storage as $mail){
    echo $mail->subject();
    echo strip_tags($mail->getContent());
}

I'm accessing the mail using google oAuth. $this->label is the folder I want to get. It's quite simple for now but before making it to complex I want to figure out the fundamentals such as a suitable way to extract all above listed data into separate keys in an array.

Was it helpful?

Solution

You can get the headers for sender, receiver and date quite easily using the same technique you used for the subject, however the actual plaintext body is a bit more tricky, here's a sample code which will do what you want

    $this->gOauth = new GoogleOauth();
    $this->gOauth->connect_imap();
    $storage = new Zend_Mail_Storage_Imap(&$this->gOauth->gImap);
    $storage->selectFolder($this->label);
    // output first text/plain part
    $foundPart = null;
    foreach($storage as $mail){
        echo '----------------------<br />'."\n";
        echo "From: ".utf8_encode($mail->from)."<br />\n";
        echo "To: ".utf8_encode(htmlentities($mail->to))."<br />\n";
        echo "Time: ".utf8_encode(htmlentities(date("Y-m-d H:s" ,strtotime($mail->date))))."<br />\n";
        echo "Subject: ".utf8_encode($mail->subject)."<br />\n";

        foreach (new RecursiveIteratorIterator($mail) as $part) {
            try {
                if (strtok($part->contentType, ';') == 'text/plain') {
                    $foundPart = $part;
                    break;
                }
            } catch (Zend_Mail_Exception $e) {
                // ignore
            }
        }
        if (!$foundPart) {
            echo "no plain text part found <br /><br /><br /><br />\n\n\n";
        } else {
            echo "plain text part: <br />" .
                    str_replace("\n", "\n<br />", trim(utf8_encode(quoted_printable_decode(strip_tags($foundPart)))))
                ." <br /><br /><br /><br />\n\n\n";
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top