ezcMailImapTransport::top PHP Метод

top() публичный Метод

This method supports unique IDs instead of message numbers. See {@link ezcMailImapTransportOptions} for how to enable unique IDs referencing. If the command failed or if it was not supported by the server an empty string is returned. This method is useful for retrieving the headers of messages from the mailbox as strings, which can be later parsed with {@link ezcMailParser} and {@link ezcMailVariableSet}. In this way the retrieval of the full messages from the server is avoided when building a list of messages. Before calling this method, a connection to the IMAP server must be established and a user must be authenticated successfully, and a mailbox must be selected. Example of listing the mail headers of all the messages in the current mailbox: $imap = new ezcMailImapTransport( 'imap.example.com' ); $imap->authenticate( 'username', 'password' ); $imap->selectMailbox( 'Inbox' ); $parser = new ezcMailParser(); $messages = $imap->listMessages(); foreach ( $messages as $messageNr => $size ) { $set = new ezcMailVariableSet( $imap->top( $messageNr ) ); $mail = $parser->parseMail( $set ); $mail = $mail[0]; echo "From: {$mail->from}, Subject: {$mail->subject}, Size: {$size}\n"; } For a more advanced example see the "Mail listing example" in the online documentation.
public top ( integer $msgNum, integer $chars ) : string
$msgNum integer
$chars integer
Результат string
    public function top($msgNum, $chars = 0)
    {
        $uid = $this->options->uidReferencing ? self::UID : self::NO_UID;
        if ($this->state != self::STATE_SELECTED && $this->state != self::STATE_SELECTED_READONLY) {
            throw new ezcMailTransportException("Can't call top() on the IMAP transport when a mailbox is not selected.");
        }
        $tag = $this->getNextTag();
        if ($chars === 0) {
            $command = "{$tag} {$uid}FETCH {$msgNum} (BODY.PEEK[HEADER] BODY.PEEK[TEXT])";
        } else {
            $command = "{$tag} {$uid}FETCH {$msgNum} (BODY.PEEK[HEADER] BODY.PEEK[TEXT]<0.{$chars}>)";
        }
        $this->connection->sendData($command);
        if ($this->options->uidReferencing) {
            // special case (BUG?) where "UID FETCH {$msgNum}" returns nothing
            $response = trim($this->connection->getLine());
            if ($this->responseType($response) === self::RESPONSE_OK) {
                throw new ezcMailTransportException("The IMAP server could not fetch the message '{$msgNum}': {$response}.");
            }
        } else {
            $response = $this->getResponse('FETCH (');
        }
        $message = "";
        if (strpos($response, 'FETCH (') !== false) {
            // Added hack for issue #14360: problems with $imap->top() command in gmail.
            if ($this->serverType === self::SERVER_GIMAP) {
                // Google IMAP servers return the body first, then the headers (!)
                $bytesToRead = $this->getMessageSectionSize($response);
                $response = "";
                while ($bytesToRead >= 0) {
                    $data = $this->connection->getLine();
                    $lastResponse = $data;
                    $bytesToRead -= strlen($data);
                    // in case reading too much and the string "BODY[HEADER] {size}"
                    // is at the end of the last line
                    if ($bytesToRead <= 0) {
                        if ($bytesToRead < 0) {
                            $lastResponse = substr($data, $bytesToRead);
                            $data = substr($data, 0, strlen($data) + $bytesToRead);
                        }
                    }
                    $message .= $data;
                }
                // Read the headers
                $headers = '';
                $response = $this->connection->getLine();
                $bytesToRead = $this->getMessageSectionSize($lastResponse);
                $response = $this->connection->getLine();
                while (strpos($response, $tag) === false) {
                    $headers .= $response;
                    $response = $this->connection->getLine();
                }
                $headers = trim($headers, ")\r\n");
                // Append the body AFTER the headers as it should be
                $message = $headers . "\r\n\r\n" . $message;
            } else {
                // Other IMAP servers return the headers first, then the body
                $response = "";
                while (strpos($response, 'BODY[TEXT]') === false) {
                    $message .= $response;
                    $response = $this->connection->getLine();
                }
                $response = $this->connection->getLine();
                while (strpos($response, $tag) === false) {
                    $message .= $response;
                    $response = $this->connection->getLine();
                }
            }
        }
        // skip the OK response ("{$tag} OK Fetch completed.")
        $response = trim($this->getResponse($tag, $response));
        if ($this->responseType($response) != self::RESPONSE_OK) {
            throw new ezcMailTransportException("The IMAP server could not fetch the message '{$msgNum}': {$response}.");
        }
        return $message;
    }

Usage Example

Пример #1
0
$messages = $transport->listMessages();
// Calculate how many pages of mails there will be based on pageSize
$numberOfPages = (int) floor(count($messages) / $options["pageSize"] + 1);
// See if currentPage fits in the range 1..numberOfPages
if ($options["currentPage"] <= 0 || $options["currentPage"] > $numberOfPages || count($messages) % $options["pageSize"] === 0 && $options["currentPage"] >= $numberOfPages) {
    $options["currentPage"] = 1;
}
// Slice the array to the range defined by currentPage
$sizes = array_slice(array_values($messages), ($options["currentPage"] - 1) * $options["pageSize"], $options["pageSize"]);
$mailIDs = array_slice($mailIDs, ($options["currentPage"] - 1) * $options["pageSize"], $options["pageSize"]);
$messages = array_keys($messages);
// Read and parse the headers of the mails in the currentPage from the IMAP server
$mails = array();
$parser = new ezcMailParser();
for ($i = ($options["currentPage"] - 1) * $options["pageSize"]; $i < min($options["currentPage"] * $options["pageSize"], count($messages)); $i++) {
    $msg = $transport->top($messages[$i]);
    $lines = preg_split("/\r\n|\n/", $msg);
    $msg = null;
    foreach ($lines as $line) {
        // eliminate the line that contains "Content-Type" at it would throw
        // a notice for "multipart/related" (because the multipart object cannot
        // be created due to missing the body)
        if (stripos($line, "Content-Type:") === false) {
            $msg .= $line . PHP_EOL;
        } else {
            // insert code to analyse the Content-Type of the mail
            // and add an "attachment" icon in case it is "multipart"
        }
    }
    $set = new ezcMailVariableSet($msg);
    $mail = $parser->parseMail($set);
All Usage Examples Of ezcMailImapTransport::top