/** * Lista o cabeçalho das 100 primeiras mensagens armazenadas * * @param string $textSearch * @return \ZendT_Mail_Service_HeaderMessage[] */ public function listHeaderMessages($textSearch = 'ALL') { $itens = array(); $messages = $this->getMailsInfo($this->searchMailbox($textSearch)); $limitMessage = 100; $iMessage = 0; foreach ($messages as $message) { if ($iMessage == $limitMessage) { break; } $head = imap_rfc822_parse_headers(imap_fetchheader($this->getImapStream(), $message->uid, FT_UID)); $item = new ZendT_Mail_HeaderMessage(); $item->id = $head->message_id; $item->dateTime = date('Y-m-d H:i:s', isset($head->date) ? strtotime($head->date) : time()); $item->subject = $this->decodeMimeStr($head->subject, $this->serverEncoding); $item->from = strtolower($head->from[0]->mailbox . '@' . $head->from[0]->host); $toStrings = array(); foreach ($head->to as $to) { if (!empty($to->mailbox) && !empty($to->host)) { $toEmail = strtolower($to->mailbox . '@' . $to->host); $toName = isset($to->personal) ? $this->decodeMimeStr($to->personal, $this->serverEncoding) : null; $toStrings[] = $toName ? "{$toName} <{$toEmail}>" : $toEmail; } } $item->to = implode(', ', $toStrings); $itens[] = $item; $iMessage++; } return $itens; }
function getHeaders($mid) { if (!$this->marubox) { return false; } $mail_header = @imap_fetchheader($this->marubox, $mid); if ($mail_header == false) { return false; } $mail_header = imap_rfc822_parse_headers($mail_header); $sender = isset($mail_header->from[0]) ? $mail_header->from[0] : ''; $sender_replyto = isset($mail_header->reply_to[0]) ? $mail_header->reply_to[0] : ''; if (strtolower($sender->mailbox) != 'mailer-daemon' && strtolower($sender->mailbox) != 'postmaster') { $newvalue['personal'] = $this->email_Decode($sender->personal); $newvalue['sender_personal'] = $this->email_Decode($sender_replyto->personal); $newvalue['subject'] = $this->email_Decode($mail_header->subject); $newvalue['toaddress'] = isset($mail_header->toaddress) ? $this->email_Decode($mail_header->toaddress) : ''; $mail_header = (array) $mail_header; $sender = (array) $sender; $mail_details = array('feid' => imap_uid($this->marubox, $mid), 'from' => strtolower($sender['mailbox']) . '@' . $sender['host'], 'from_name' => $newvalue['personal'], 'to_other' => strtolower($sender_replyto->mailbox) . '@' . $sender_replyto->host, 'toname_other' => $newvalue['sender_personal'], 'subjects' => $newvalue['subject'], 'to' => $newvalue['toaddress'], 'time' => strtotime($mail_header['Date'])); } return $mail_details; }
private function parseHeader() { $header = imap_fetchheader($this->client->connection, $this->uid, FT_UID); if ($header) { $header = imap_rfc822_parse_headers($header); } if (property_exists($header, 'subject')) { $this->subject = imap_utf8($header->subject); } if (property_exists($header, 'date')) { $this->date = Carbon::parse($header->date); } if (property_exists($header, 'from')) { $this->from = $this->parseAddresses($header->from); } if (property_exists($header, 'to')) { $this->to = $this->parseAddresses($header->to); } if (property_exists($header, 'cc')) { $this->cc = $this->parseAddresses($header->cc); } if (property_exists($header, 'bcc')) { $this->bcc = $this->parseAddresses($header->bcc); } if (property_exists($header, 'reply_to')) { $this->reply_to = $this->parseAddresses($header->reply_to); } if (property_exists($header, 'sender')) { $this->sender = $this->parseAddresses($header->sender); } if (property_exists($header, 'message_id')) { $this->message_id = str_replace(['<', '>'], '', $header->message_id); } if (property_exists($header, 'Msgno')) { $this->message_no = trim($header->Msgno); } }
private function fetchHeaders($imapResource, $uid) { return \imap_rfc822_parse_headers(\imap_fetchheader($imapResource, $uid, \FT_UID)); }
protected function parse($rawmessage) { parent::parse($rawmessage); $headers = imap_rfc822_parse_headers($this->rawheader, self::INTERNAL_HOST); if (isset($headers->udate)) { $this->date = $headers->udate; } else { if (isset($headers->date) && ($date = \Zeyon\parseTime($headers->date)) !== null) { $this->date = $date; } } isset($headers->subject) and $this->subject = self::decodeHeader($headers->subject); if (isset($headers->fromaddress)) { $address = $headers->from[0]; $this->sender = self::decodeHeader($headers->fromaddress); $this->sender_email = isset($address->mailbox, $address->host) ? "{$address->mailbox}@{$address->host}" : ''; $this->sender_name = isset($address->personal) ? self::decodeHeader($address->personal) : $this->sender_email; } if (isset($headers->toaddress)) { $address = $headers->to[0]; $this->to = self::decodeHeader($headers->toaddress); $this->to_email = isset($address->mailbox, $address->host) ? "{$address->mailbox}@{$address->host}" : ''; $this->to_name = isset($address->personal) ? self::decodeHeader($address->personal) : $this->to_email; $this->to_count = count($headers->to); } isset($headers->ccaddress) and $this->cc = self::decodeHeader($headers->ccaddress); isset($headers->bccaddress) and $this->bcc = self::decodeHeader($headers->bccaddress); isset($headers->reply_toaddress) and $this->replyto = self::decodeHeader($headers->reply_toaddress); $this->receipt = self::extractHeaderField($this->rawheader, 'Disposition-Notification-To') !== '' || self::extractHeaderField($this->rawheader, 'Return-Receipt-To') !== ''; $this->spam = strtolower(self::extractHeaderField($this->rawheader, 'X-Spam-Flag')) === 'yes' || preg_match('/^\\s*\\[spam\\]/i', $this->subject); }
/** * Secret Sauce - Transform an email string * response to array key value format * * @param *string $email The actual email * @param string|null $uniqueId The mail UID * @param array $flags Any mail flags * * @return array */ private function getEmailFormat($email, $uniqueId = null, array $flags = array()) { //if email is an array if (is_array($email)) { //make it into a string $email = implode("\n", $email); } //split the head and the body $parts = preg_split("/\n\\s*\n/", $email, 2); $head = $parts[0]; $body = null; if (isset($parts[1]) && trim($parts[1]) != ')') { $body = $parts[1]; } $lines = explode("\n", $head); $head = array(); foreach ($lines as $line) { if (trim($line) && preg_match("/^\\s+/", $line)) { $head[count($head) - 1] .= ' ' . trim($line); continue; } $head[] = trim($line); } $head = implode("\n", $head); $recipientsTo = $recipientsCc = $recipientsBcc = $sender = array(); //get the headers $headers1 = imap_rfc822_parse_headers($head); $headers2 = $this->getHeaders($head); //set the from $sender['name'] = null; if (isset($headers1->from[0]->personal)) { $sender['name'] = $headers1->from[0]->personal; //if the name is iso or utf encoded if (preg_match("/^\\=\\?[a-zA-Z]+\\-[0-9]+.*\\?/", strtolower($sender['name']))) { //decode the subject $sender['name'] = str_replace('_', ' ', mb_decode_mimeheader($sender['name'])); } } $sender['email'] = $headers1->from[0]->mailbox . '@' . $headers1->from[0]->host; //set the to if (isset($headers1->to)) { foreach ($headers1->to as $to) { if (!isset($to->mailbox, $to->host)) { continue; } $recipient = array('name' => null); if (isset($to->personal)) { $recipient['name'] = $to->personal; //if the name is iso or utf encoded if (preg_match("/^\\=\\?[a-zA-Z]+\\-[0-9]+.*\\?/", strtolower($recipient['name']))) { //decode the subject $recipient['name'] = str_replace('_', ' ', mb_decode_mimeheader($recipient['name'])); } } $recipient['email'] = $to->mailbox . '@' . $to->host; $recipientsTo[] = $recipient; } } //set the cc if (isset($headers1->cc)) { foreach ($headers1->cc as $cc) { $recipient = array('name' => null); if (isset($cc->personal)) { $recipient['name'] = $cc->personal; //if the name is iso or utf encoded if (preg_match("/^\\=\\?[a-zA-Z]+\\-[0-9]+.*\\?/", strtolower($recipient['name']))) { //decode the subject $recipient['name'] = str_replace('_', ' ', mb_decode_mimeheader($recipient['name'])); } } $recipient['email'] = $cc->mailbox . '@' . $cc->host; $recipientsCc[] = $recipient; } } //set the bcc if (isset($headers1->bcc)) { foreach ($headers1->bcc as $bcc) { $recipient = array('name' => null); if (isset($bcc->personal)) { $recipient['name'] = $bcc->personal; //if the name is iso or utf encoded if (preg_match("/^\\=\\?[a-zA-Z]+\\-[0-9]+.*\\?/", strtolower($recipient['name']))) { //decode the subject $recipient['name'] = str_replace('_', ' ', mb_decode_mimeheader($recipient['name'])); } } $recipient['email'] = $bcc->mailbox . '@' . $bcc->host; $recipientsBcc[] = $recipient; } } //if subject is not set if (!isset($headers1->subject) || strlen(trim($headers1->subject)) === 0) { //set subject $headers1->subject = self::NO_SUBJECT; } //trim the subject $headers1->subject = str_replace(array('<', '>'), '', trim($headers1->subject)); //if the subject is iso or utf encoded if (preg_match("/^\\=\\?[a-zA-Z]+\\-[0-9]+.*\\?/", strtolower($headers1->subject))) { //decode the subject $headers1->subject = str_replace('_', ' ', mb_decode_mimeheader($headers1->subject)); } //set thread details $topic = isset($headers2['thread-topic']) ? $headers2['thread-topic'] : $headers1->subject; $parent = isset($headers2['in-reply-to']) ? str_replace('"', '', $headers2['in-reply-to']) : null; //set date $date = isset($headers1->date) ? strtotime($headers1->date) : null; //set message id if (isset($headers2['message-id'])) { $messageId = str_replace('"', '', $headers2['message-id']); } else { $messageId = '<eden-no-id-' . md5(uniqid()) . '>'; } $attachment = isset($headers2['content-type']) && strpos($headers2['content-type'], 'multipart/mixed') === 0; $format = array('id' => $messageId, 'parent' => $parent, 'topic' => $topic, 'mailbox' => $this->mailbox, 'uid' => $uniqueId, 'date' => $date, 'subject' => str_replace('’', '\'', $headers1->subject), 'from' => $sender, 'flags' => $flags, 'to' => $recipientsTo, 'cc' => $recipientsCc, 'bcc' => $recipientsBcc, 'attachment' => $attachment); if (trim($body) && $body != ')') { //get the body parts $parts = $this->getParts($email); //if there are no parts if (empty($parts)) { //just make the body as a single part $parts = array('text/plain' => $body); } //set body to the body parts $body = $parts; //look for attachments $attachment = array(); //if there is an attachment in the body if (isset($body['attachment'])) { //take it out $attachment = $body['attachment']; unset($body['attachment']); } $format['body'] = $body; $format['attachment'] = $attachment; } return $format; }
/** * SEARCH IMAP * @param Mixed $filter search filter as String or as Array of searches * @param string $params option filter params * @return mixed $data emails */ private function _search($filter = "ALL", $params = null) { if (is_array($filter)) { $emails = array(); foreach ($filter as $string) { $search = imap_search($this->imap, $string); if ($search) { $emails = array_merge($emails, $search); } } } else { $emails = imap_search($this->imap, $filter . " " . $params); } /* if emails are returned, cycle through each... */ $data = array(); if ($emails) { /* for every email... */ foreach ($emails as $email_number) { /* get information specific to this email */ $overview = imap_fetch_overview($this->imap, $email_number, 0); $this->structure = imap_fetchstructure($this->imap, $email_number, 0); /* commented out to speed up email retrieval */ $headers = imap_rfc822_parse_headers(imap_fetchheader($this->imap, $email_number)); switch (strtolower($this->structure->subtype)) { case "plain": $partNum = 1; break; case "alternative": $partNum = 1; break; case "mixed": $partNum = 1.2; break; case "html": $partNum = 1.2; break; } $partNum = 1; $message = quoted_printable_decode(imap_fetchbody($this->imap, $email_number, $partNum, FT_PEEK)); /* get any possible attachments, commented out to speed up email retrieval, we do not want to do this unless we are automatically associating an email with a user */ // $attachments = $this->getAttachments($email_number); $email = array('overview' => $overview[0], 'structure' => $this->structure, 'headers' => $headers, 'message' => $message); $data[$email_number] = $email; } } return $data; }
/** * Get message headers * * @return Message\Headers */ public function getHeaders() { if (null === $this->headers) { $headers = imap_rfc822_parse_headers($this->getPlainHeader()); // check errors. $lastError = imap_last_error(); if ($lastError !== false) { if (1 === preg_match('/Unexpected characters at end of address: <(.*)>/', $lastError, $matches)) { /** * Message parsing from, to, cc headers exception occurs. * It's not critical, because problem can be located just in single address from many. * So we can proceed this letter, just drop the notice. */ imap_errors(); } } $this->headers = new Message\Headers($headers); } return $this->headers; }
function getMessageHeader($_uid, $_partID = '') { $msgno = imap_msgno($this->mbox, $_uid); if ($_partID == '') { $retValue = imap_header($this->mbox, $msgno); } else { // do it the hard way // we need to fetch the headers of another part(message/rfcxxxx) $headersPart = imap_fetchbody($this->mbox, $_uid, $_partID . ".0", FT_UID); $retValue = imap_rfc822_parse_headers($headersPart); } #_debug_array($retValue); return $retValue; }
/** * Return headers. Parameter are: date, subject, message_id, to, from. * * @param string $head * @return hash */ public function parseHeaders($head) { $h = imap_rfc822_parse_headers($head); $p = array(); $p['date'] = $h->date; $p['subject'] = $h->subject; $p['message_id'] = $h->message_id; $p['to'] = $h->toaddress; // $h->reply_toaddress, $h->senderaddress $p['from'] = $h->fromaddress; return $p; }
/** * Método que entrega rescata un mensaje desde la casilla de correo * @param uid UID del mensaje que se desea obtener * @param filter Arreglo con filtros a usar para las partes del mensaje. Ej: ['subtype'=>['PLAIN', 'XML'], 'extension'=>['xml']] * @return Arreglo con los datos del mensaje, índices: header, body, charset y attachments * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]delaf.cl) * @version 2016-11-24 */ public function getMessage($uid, $filter = []) { $message = ['header' => imap_rfc822_parse_headers(imap_fetchheader($this->link, $uid, FT_UID)), 'body' => ['plain' => '', 'html' => ''], 'charset' => '', 'attachments' => []]; $s = imap_fetchstructure($this->link, $uid, FT_UID); if (!is_object($s)) { return false; } // el correo es simple y no tiene múltiples partes if (empty($s->parts)) { $this->getMessagePart($uid, $s, 0, $message); } else { foreach ($s->parts as $partno0 => $p) { if (!$filter) { $this->getMessagePart($uid, $p, $partno0 + 1, $message); } else { // si es del subtipo de agrega $subtype = isset($filter['subtype']) ? array_map('strtoupper', $filter['subtype']) : []; if (in_array(strtoupper($p->subtype), $subtype)) { $this->getMessagePart($uid, $p, $partno0 + 1, $message); } else { if (isset($filter['extension']) and ($p->ifdisposition and strtoupper($p->disposition) == 'ATTACHMENT' or $p->subtype == 'OCTET-STREAM' and ($p->ifparameters or $p->ifdparameters))) { $extension = array_map('strtolower', $filter['extension']); $add = false; $params = $p->ifparameters ? $p->parameters : ($p->ifdparameters ? $p->dparameters : []); foreach ($params as $parameter) { $value = strpos($parameter->value, '=?UTF-8?Q?') === 0 ? imap_utf8($parameter->value) : $parameter->value; if (in_array(strtolower(substr($value, -3)), $extension)) { $add = true; break; } } if ($add) { $this->getMessagePart($uid, $p, $partno0 + 1, $message, true); } } } } } } // decodificar $message['header']->subject = utf8_encode(imap_mime_header_decode($message['header']->subject)[0]->text); // entregar mensaje return $message; }
/** * Set member variable containing header information. Creates an array containing associative indices * referring to various header information. Use {@link var_dump} or {@link print_r} on the {@link $header} * member variable to view information gathered by this function. * * Returns header information on success and FALSE on failure. * * @param int &$mid message id * @param string &$pid part id * @param int $from_length (optional) from length for imap_headerinfo * @param int $subject_length (optional) subject length for imap_headerinfo * @param string $default_host (optional) default host for imap_headerinfo & imap_rfc822_parse_headers * @param int $options (optional) flags/options for imap_fetchbody (DEPRECATED, use $this->option['fetchbody']) * @return Array|BOOL * @access public * @see getParts * @see imap_fetchheader * @see imap_fetchbody * @see imap_headerinfo * @see imap_rfc822_parse_headers */ function getHeaders(&$mid, $pid = '0', $from_length = 1024, $subject_length = 1024, $default_host = NULL, $options = NULL) { if (FALSE === ($hpid = Mail_IMAP::getRawHeaders($mid, $pid, $options, FALSE))) { return FALSE; } // $default_host contains the host information for addresses where it is not // present. Specify it or attempt to use SERVER_NAME if ($default_host == NULL && isset($_SERVER['SERVER_NAME']) && !empty($_SERVER['SERVER_NAME'])) { $default_host = $_SERVER['SERVER_NAME']; } else { if ($default_host == NULL) { $default_host = 'UNSPECIFIED-HOST-NAME'; } } // Parse the headers $header_info = $hpid == '0' ? imap_headerinfo($this->mailbox, $mid, $from_length, $subject_length, $default_host) : imap_rfc822_parse_headers($this->rawHeaders[$mid], $default_host); // Since individual member variable creation might create extra overhead, // and having individual variables referencing this data and the original // object would be too much as well, we'll just copy the object into an // associative array, preform clean-up on those elements that require it, // and destroy the original object after copying. if (!is_object($header_info)) { PEAR::raiseError('Mail_IMAP::getHeaders: Unable to retrieve header object, invalid part id: ' . $pid, NULL, PEAR_ERROR_TRIGGER, E_USER_WARNING); return FALSE; } $headers = get_object_vars($header_info); foreach ($headers as $key => $value) { if (!is_object($value) && !is_array($value)) { $this->header[$mid][$key] = $value; } } // copy udate or create it from date string. $this->header[$mid]['udate'] = isset($header_info->udate) && !empty($header_info->udate) ? $header_info->udate : strtotime($header_info->Date); // clean up addresses $line[] = 'from'; $line[] = 'reply_to'; $line[] = 'sender'; $line[] = 'return_path'; $line[] = 'to'; $line[] = 'cc'; $line[] = 'bcc'; for ($i = 0; $i < count($line); $i++) { if (isset($header_info->{$line}[$i])) { Mail_IMAP::_parseHeaderLine($mid, $header_info->{$line}[$i], $line[$i]); } } // All possible information has been copied, destroy original object unset($header_info); return $this->header[$mid]; }
<?php session_start(); $uid = $_GET['uid']; $gmail = 'gmail.com'; $yahoo = 'mail.yahoo.com'; $mbox = imap_open("{imap." . $_COOKIE['boxmail'] . ":993/imap/ssl}", $_COOKIE['email'], $_COOKIE['pass']); if (FALSE === $mbox) { die('echec !!!'); } else { $headerText = imap_fetchHeader($mbox, $uid, FT_UID); $header = imap_rfc822_parse_headers($headerText); // REM: Attention s'il y a plusieurs sections $corps = imap_fetchbody($mbox, $uid, 1, FT_UID); } imap_close($mbox); $from = $header->from; $msg = "Message de:" . $from[0]->personal . " [" . $from[0]->mailbox . "@" . $from[0]->host . "]<br>"; $msg .= $corps; include '../../vue/formulaire/Info.php';
/** * Takes the "parts" attribute of the object that imap_fetchbody() method * returns, and recursively goes through looking for objects that have a * disposition of "attachement" or "inline" * @param int $msgNo The relative message number for the monitored mailbox * @param object $parts Array of objects to examine * @param string $emailId The GUID of the email saved prior to calling this method * @param array $breadcrumb Default 0, build up of the parts mapping * @param bool $forDisplay Default false */ function saveAttachments($msgNo, $parts, $emailId, $breadcrumb = '0', $forDisplay) { global $sugar_config; /* Primary body types for a part of a mail structure (imap_fetchstructure returned object) 0 => text 1 => multipart 2 => message 3 => application 4 => audio 5 => image 6 => video 7 => other */ foreach ($parts as $k => $part) { $thisBc = $k + 1; if ($breadcrumb != '0') { $thisBc = $breadcrumb . '.' . $thisBc; } $attach = null; // check if we need to recurse into the object //if($part->type == 1 && !empty($part->parts)) { if (isset($part->parts) && !empty($part->parts) && !(isset($part->subtype) && strtolower($part->subtype) == 'rfc822')) { $this->saveAttachments($msgNo, $part->parts, $emailId, $thisBc, $forDisplay); continue; } elseif ($part->ifdisposition && strtolower($part->subtype) != 'rfc822') { // we will take either 'attachments' or 'inline' if (strtolower($part->disposition) == 'attachment' || strtolower($part->disposition) == 'inline' && $part->type != 0) { $attach = $this->getNoteBeanForAttachment($emailId); $fname = $this->handleEncodedFilename($this->retrieveAttachmentNameFromStructure($part)); if (!empty($fname)) { //assign name to attachment $attach->name = $fname; } else { //if name is empty, default to filename $attach->name = urlencode($this->retrieveAttachmentNameFromStructure($part)); } $attach->filename = $attach->name; if (empty($attach->filename)) { continue; } // deal with the MIME types email has $attach->file_mime_type = $this->getMimeType($part->type, $part->subtype); $attach->safeAttachmentName(); if ($forDisplay) { $attach->id = $this->getTempFilename(); } else { // only save if doing a full import, else we want only the binaries $attach->save(); } } // end if disposition type 'attachment' } elseif ($part->type == 2 && isset($part->subtype) && strtolower($part->subtype) == 'rfc822') { $tmp_eml = imap_fetchbody($this->conn, $msgNo, $thisBc); $rfcheaders = imap_rfc822_parse_headers($tmp_eml); $attach = $this->getNoteBeanForAttachment($emailId); $attach->file_mime_type = 'message/rfc822'; $attach->description = $tmp_eml; $attach->filename = $attach->name = $rfcheaders->subject . ".eml"; $attach->safeAttachmentName(); if ($forDisplay) { $attach->id = $this->getTempFilename(); } else { // only save if doing a full import, else we want only the binaries $attach->save(); } } elseif (!$part->ifdisposition && $part->type != 1 && $part->type != 2 && $thisBc != '1') { // No disposition here, but some IMAP servers lie about disposition headers, try to find the truth // Also Outlook puts inline attachments as type 5 (image) without a disposition if ($part->ifparameters) { foreach ($part->parameters as $param) { if (strtolower($param->attribute) == "name" || strtolower($param->attribute) == "filename") { $fname = $this->handleEncodedFilename($param->value); break; } } if (empty($fname)) { continue; } // we assume that named parts are attachments too $attach = $this->getNoteBeanForAttachment($emailId); $attach->filename = $attach->name = $fname; $attach->file_mime_type = $this->getMimeType($part->type, $part->subtype); $attach->safeAttachmentName(); if ($forDisplay) { $attach->id = $this->getTempFilename(); } else { // only save if doing a full import, else we want only the binaries $attach->save(); } } } $this->saveAttachmentBinaries($attach, $msgNo, $thisBc, $part, $forDisplay); } // end foreach }
function getHeaders() { if ($this->headers === null) { $this->headers = imap_rfc822_parse_headers($this->getRawHeaders()); } return $this->headers; }
/** * Get mail data * * @param $mailId * @param bool $markAsSeen * * @return Mail */ public function getMail($mailId, $markAsSeen = true) { $header = imap_fetchheader($this->getImapStream(), $mailId, FT_UID); $headObject = imap_rfc822_parse_headers($header); $mail = new Message(); $mail->id = $mailId; $mail->date = date('Y-m-d H:i:s', isset($headObject->date) ? strtotime(preg_replace('/\\(.*?\\)/', '', $headObject->date)) : time()); $mail->subject = isset($headObject->subject) ? $this->decodeMimeStr($headObject->subject, $this->serverEncoding) : null; $mail->fromName = isset($headObject->from[0]->personal) ? $this->decodeMimeStr($headObject->from[0]->personal, $this->serverEncoding) : null; $mail->fromAddress = strtolower($headObject->from[0]->mailbox . '@' . $headObject->from[0]->host); if (isset($headObject->to)) { $toStrings = []; foreach ($headObject->to as $to) { if (!empty($to->mailbox) && !empty($to->host)) { $toEmail = strtolower($to->mailbox . '@' . $to->host); $toName = isset($to->personal) ? $this->decodeMimeStr($to->personal, $this->serverEncoding) : null; $toStrings[] = $toName ? "{$toName} <{$toEmail}>" : $toEmail; $mail->to[$toEmail] = $toName; } } $mail->toString = implode(', ', $toStrings); } if (isset($headObject->cc)) { foreach ($headObject->cc as $cc) { $mail->cc[strtolower($cc->mailbox . '@' . $cc->host)] = isset($cc->personal) ? $this->decodeMimeStr($cc->personal, $this->serverEncoding) : null; } } if (isset($headObject->reply_to)) { foreach ($headObject->reply_to as $replyTo) { $mail->replyTo[strtolower($replyTo->mailbox . '@' . $replyTo->host)] = isset($replyTo->personal) ? $this->decodeMimeStr($replyTo->personal, $this->serverEncoding) : null; } } $mailStructure = imap_fetchstructure($this->getImapStream(), $mailId, FT_UID); if (empty($mailStructure->parts)) { $this->initMailPart($mail, $mailStructure, 0, $markAsSeen); } else { foreach ($mailStructure->parts as $partNum => $partStructure) { $this->initMailPart($mail, $partStructure, $partNum + 1, $markAsSeen); } } // Parse X headers $tempArray = explode("\n", $header); if (is_array($tempArray) && count($tempArray)) { $headers = []; foreach ($tempArray as $line) { if (preg_match("/^X-(.*?): (.*?)\$/is", trim($line), $matches)) { $headers['x-' . strtolower($matches[1])] = $matches[2]; } } $mail->xHeaders = $headers; } return $mail; }
public function readMessage($msgno, $types = null) { if ($this->mailLocalStorage->has($msgno)) { return $this->mailLocalStorage->get($msgno); } $head = imap_rfc822_parse_headers(imap_fetchheader($this->connection, $msgno, FT_UID)); $mail = new IncomingMail($msgno); $mail->date = isset($head->date) ? strtotime($head->date) : time(); $mail->subject = isset($head->subject) ? static::decode($head->subject, $this->imap->serverEncoding) : null; $mail->fromName = isset($head->from[0]->personal) ? static::decode($head->from[0]->personal, $this->imap->serverEncoding) : null; $mail->fromAddress = strtolower($head->from[0]->mailbox . '@' . $head->from[0]->host); if (isset($head->to)) { $toList = array(); foreach ($head->to as $to) { if (!empty($to->mailbox) && !empty($to->host)) { $toEmail = (string) strtolower($to->mailbox . '@' . $to->host); $toName = (string) isset($to->personal) ? static::decode($to->personal, $this->imap->serverEncoding) : null; $toList[] = $toName ? "{$toName} <{$toEmail}>" : $toEmail; $mail->to[$toEmail] = $toName; } } $mail->toString = implode(', ', $toList); } if (isset($head->cc)) { foreach ($head->cc as $cc) { $mail->cc[strtolower($cc->mailbox . '@' . $cc->host)] = isset($cc->personal) ? static::decode($cc->personal, $this->imap->serverEncoding) : null; } } if (isset($head->reply_to)) { $replyToString = []; foreach ($head->reply_to as $replyTo) { $email = strtolower($replyTo->mailbox . '@' . $replyTo->host); $name = isset($replyTo->personal) ? static::decode($replyTo->personal, $this->imap->serverEncoding) : $email; $mail->replyTo[$email] = $name; $replyToString[] = "{$name} <{$email}>"; } $mail->replyToString = implode(',', $replyToString); } $reader = new MailReader($this->imap, $mail, $this->attachmentsDirectory); $reader->read($types); $this->mailLocalStorage->set($msgno, $mail); return $mail; }
/** * Recupera o conjunto de cabeçalhos interpretados segundo a RFC-822 * @return stdClass */ public function getRFC822Headers() { return (object) $this->parseHeaders( (array) imap_rfc822_parse_headers( $this->headers ) ); }
/** * Set member variable containing header information. Creates an array containing * associative indices referring to various header information. Use {@link var_dump} * or {@link print_r} on the {@link $header} member variable to view information * gathered by this function. * * If $ret is true, returns array containing header information on success and false * on failure. * * If $ret is false, adds the header information to the $header member variable * and returns BOOL. * * @param int &$mid message id * @param string &$pid (optional) part id to retrieve headers for. * @param bool $rtn * (optional) If true return the headers, if false, assign to $header member variable. * * @param array $args * (optional) Associative array containing extra arguments. * * $args['from_length'] int * From field length for imap_headerinfo. * * $args['subject_length'] int * Subject field length for imap_headerinfo * * $args['default_host'] string * Default host for imap_headerinfo & imap_rfc822_parse_headers * * @return Array|BOOL * @tutorial http://www.smilingsouls.net/Mail_IMAP?content=Mail_IMAP/getHeaders * @access public * @see getParts * @see imap_fetchheader * @see imap_fetchbody * @see imap_headerinfo * @see imap_rfc822_parse_headers */ function getHeaders(&$mid, $pid = '0', $rtn = false, $args = array()) { $this->_checkIfParsed($mid); if ($pid == $this->msg[$mid]['pid']) { $pid = '0'; } if ($pid !== '0') { if (false === ($raw_headers = $this->getRawHeaders($mid, $pid, true, true))) { return false; } if ($raw_headers === true) { $pid = '0'; } } if (!isset($args['from_length'])) { $args['from_length'] = 1024; } if (!isset($args['subject_length'])) { $args['subject_length'] = 1024; } if (!isset($args['default_host'])) { $args['default_host'] = null; } // Parse the headers $header_info = $pid === '0' ? imap_headerinfo($this->mailbox, $mid, $args['from_length'], $args['subject_length'], $args['default_host']) : imap_rfc822_parse_headers($raw_headers, $args['default_host']); // Since individual member variable creation might create extra overhead, // and having individual variables referencing this data and the original // object would be too much as well, we'll just copy the object into an // associative array, preform clean-up on those elements that require it, // and destroy the original object after copying. if (!is_object($header_info)) { $this->error->push(Mail_IMAPv2_ERROR_INVALID_PID, 'error', array('pid' => $pid)); return false; } $headers = get_object_vars($header_info); foreach ($headers as $key => $value) { if (!is_object($value) && !is_array($value)) { // Decode all the headers using utf8_decode(imap_utf8()) $this->header[$mid][$key] = utf8_decode(imap_utf8($value)); } } // copy udate or create it from date string. $this->header[$mid]['udate'] = isset($header_info->udate) && !empty($header_info->udate) ? $header_info->udate : strtotime($header_info->Date); // clean up addresses $line = array('from', 'reply_to', 'sender', 'return_path', 'to', 'cc', 'bcc'); for ($i = 0; $i < count($line); $i++) { if (isset($header_info->{$line}[$i])) { $this->_parseHeaderLine($mid, $header_info->{$line}[$i], $line[$i]); } } // All possible information has been copied, destroy original object unset($header_info); return $rtn ? $this->header[$mid] : false; }
private function parseHeaders() { $this->headers = imap_rfc822_parse_headers($this->raw); print_r($this->headers); }
/** * Get mail data * * @param $mail_id * @return IncomingMail */ public function get_mail($mail_id) { $head = imap_rfc822_parse_headers(imap_fetchheader($this->get_imap_stream(), $mail_id, FT_UID)); $CI =& get_instance(); $CI->load->library('Incoming_Mail'); $incoming_mail = new $CI->incoming_mail(); $incoming_mail->id = $mail_id; $incoming_mail->date = date('Y-m-d H:i:s', isset($head->date) ? strtotime($head->date) : time()); $incoming_mail->subject = isset($head->subject) ? $this->decode_mime_str($head->subject, $this->imap_server_encoding) : null; $incoming_mail->from_name = isset($head->from[0]->personal) ? $this->decode_mime_str($head->from[0]->personal, $this->imap_server_encoding) : null; $incoming_mail->from_address = strtolower($head->from[0]->mailbox . '@' . $head->from[0]->host); if (isset($head->to)) { $to_strings = array(); foreach ($head->to as $to) { if (!empty($to->mailbox) && !empty($to->host)) { $to_email = strtolower($to->mailbox . '@' . $to->host); $to_name = isset($to->personal) ? $this->decode_mime_str($to->personal, $this->imap_server_encoding) : null; $to_strings[] = $to_name ? "{$to_name} <{$to_email}>" : $to_email; $this->incoming_mail->to[$to_email] = $to_name; } } $incoming_mail->to_string = implode(', ', $to_strings); } if (isset($head->cc)) { foreach ($head->cc as $cc) { $incoming_mail->cc[strtolower($cc->mailbox . '@' . $cc->host)] = isset($cc->personal) ? $this->decode_mime_str($cc->personal, $this->imap_server_encoding) : null; } } if (isset($head->reply_to)) { foreach ($head->reply_to as $reply_to) { $incoming_mail->reply_to[strtolower($reply_to->mailbox . '@' . $reply_to->host)] = isset($reply_to->personal) ? $this->decode_mime_str($reply_to->personal, $this->imap_server_encoding) : null; } } $mail_structure = imap_fetchstructure($this->get_imap_stream(), $mail_id, FT_UID); if (empty($mail_structure->parts)) { $this->_init_mail_part($incoming_mail, $mail_structure, 0); } else { foreach ($mail_structure->parts as $part_num => $part_structure) { $this->_init_mail_part($incoming_mail, $part_structure, $part_num + 1); } } return $incoming_mail; }
/** * Reads and email and returns it as EIMapMessage class * NOTE: Attachments are automatically saved to a writtable folder. If not specified then runtime folder will be * returned instead. * @param int $msgId * @param bool $save save attachments * @return bool|Mail */ public function getMail($msgId, $save = false) { $headers = $this->imap_fetchheader($this->stream, $msgId, FT_UID); if (!$headers) { $ev = new Event(); $ev->errorMessage = 'Message with UID "' . $msgId . '" not found!'; $this->trigger(self::EVENT_IMAP_ERROR, $ev); return false; } $head = imap_rfc822_parse_headers($headers); $msg = new Mail(); $msg->UID = $msgId; $msg->date = date('Y-m-d H:i:s', isset($head->date) ? strtotime($head->date) : time()); $msg->subject = isset($head->subject) ? $this->decodeMimeString($head->subject) : null; $msg->fromName = isset($head->from[0]->personal) ? $this->decodeMimeString($head->from[0]->personal) : null; $msg->fromAddress = strtolower($head->from[0]->mailbox . '@' . $head->from[0]->host); $toStrings = []; foreach ($head->to as $to) { $toEmail = strtolower($to->mailbox . '@' . $to->host); $toName = isset($to->personal) ? $this->decodeMimeString($to->personal) : null; $toStrings[] = $toName ? "{$toName} <{$toEmail}>" : $toEmail; $msg->to[$toEmail] = $toName; } $msg->toString = implode(', ', $toStrings); if (isset($head->cc)) { foreach ($head->cc as $cc) { $msg->cc[strtolower($cc->mailbox . '@' . $cc->host)] = isset($cc->personal) ? $this->decodeMimeString($cc->personal) : null; } } if (isset($head->reply_to)) { foreach ($head->reply_to as $replyTo) { $msg->replyTo[strtolower($replyTo->mailbox . '@' . $replyTo->host)] = isset($replyTo->personal) ? $this->decodeMimeString($replyTo->personal) : null; } } $struct = imap_fetchstructure($this->stream, $msgId, FT_UID); if (empty($struct->parts)) { $this->getMailPart($msg, $struct, 0); } else { foreach ($struct->parts as $partNum => $partStruct) { $this->getMailPart($msg, $partStruct, $partNum + 1); } } $msg->textHtmlOriginal = $msg->textHtml; $msg->attachments = $this->getAttachments($msg->UID, null, $save); return $msg; }
/** * Load structure and save every part of message to common array EmbeddedMessage::$structure */ private function loadStructure() { $this->rawMimeHeader = imap_fetchmime($this->stream, $this->messageNumber, $this->partNumber, FT_UID); $this->parsedHeader = imap_rfc822_parse_headers($this->getContent()); if (!count((array) $this->parsedHeader)) { $this->parsedHeader = imap_rfc822_parse_headers($this->rawMimeHeader); } //Message ID $this->id = $this->parsedHeader->message_id; //Email from $emailFrom = $this->parsedHeader->from[0]; $emailFrom->personal = isset($emailFrom->personal) ? $emailFrom->personal : null; $this->from = new EmailAddress($emailFrom->mailbox, $emailFrom->host, imap_utf8($emailFrom->personal)); //EmailsTo $emailsTo = []; $parsedEmails = $this->parsedHeader->to; foreach ($parsedEmails as $email) { $email->personal = isset($email->personal) ? $email->personal : null; $emailsTo[] = new EmailAddress($email->mailbox, $email->host, imap_utf8($email->personal)); } $this->to = $emailsTo; //EmailsCC $emailsCc = []; $parsedEmails = isset($this->parsedHeader->cc) ? $this->parsedHeader->cc : []; foreach ($parsedEmails as $email) { $email->personal = isset($email->personal) ? $email->personal : null; $emailsCc[] = new EmailAddress($email->mailbox, $email->host, imap_utf8($email->personal)); } $this->cc = $emailsCc; //Date $this->date = new \DateTime($this->parsedHeader->date); //Subject if (preg_match('/=\\?(.*?)\\?(.*?)\\?/', $this->parsedHeader->subject, $matchSubject)) { $subjectEncoding = strtolower($matchSubject[1]); switch ($subjectEncoding) { case "utf-8": $this->subject = mb_decode_mimeheader($this->parsedHeader->subject); break; default: $this->subject = quoted_printable_decode(imap_utf8($this->parsedHeader->subject)); break; } } else { $this->subject = imap_utf8($this->parsedHeader->subject); } $this->structure = $this->parseStructure(); //extract attachments from common structure $this->attachments = $this->parseAttachments(); }
/** * Parses an email header into an array of readable and usable values. * The array will contain sub arrays of email addresses in keys "to", "from", "reply_to", "sender", "cc", "bcc" and other data. * * @param $sHeader * * @return array * @throws MailerException * */ public static function processTextHeader($sHeader) { $aResult = array(); if (!empty($sHeader) && is_string($sHeader)) { if (!function_exists('imap_rfc822_parse_headers')) { throw new MailerException('No IMAP RFC822 function available. Did you install the IMAP extension into php?'); } $oHeader = imap_rfc822_parse_headers($sHeader); $aResult = array(); $aHeaderBits = array('to', 'from', 'reply_to', 'sender', 'cc', 'bcc'); foreach ($aHeaderBits as &$sHeaderBit) { $aResult[$sHeaderBit] = array(); if (isset($oHeader->{$sHeaderBit})) { foreach ($oHeader->{$sHeaderBit} as &$sHeaderBitObject) { $aResult[$sHeaderBit][] = $sHeaderBitObject->mailbox . '@' . $sHeaderBitObject->host; } } } $aResult['date'] = $oHeader->date; $oDateTime = new \DateTime($oHeader->date); $aResult['days_ago'] = $oDateTime->diff(new \DateTime())->days; $aResult['subject'] = $oHeader->subject; $aResult['message_id'] = $oHeader->message_id; $aResult['unique_args'] = array(); $aResult['categories'] = array(); unset($oHeader, $oDateTime); foreach (explode("\n", $sHeader) as $sHeaderEntry) { if (strpos($sHeaderEntry, 'X-SMTPAPI') !== false) { $x_smtpapi = json_decode(str_replace('X-SMTPAPI: ', '', $sHeaderEntry)); if (isset($x_smtpapi->unique_args) && !empty($x_smtpapi->unique_args) && is_a($x_smtpapi->unique_args, '\\stdClass')) { $aResult['unique_args'] = get_object_vars($x_smtpapi->unique_args); } if (isset($x_smtpapi->category) && !empty($x_smtpapi->category)) { $aResult['categories'] = $x_smtpapi->category; } break; } } } return $aResult; }
/** * This function returns an object containing the headers of the message. This is done by taking the raw headers * and running them through the imap_rfc822_parse_headers function. The results are only retrieved from the server * once unless passed true as a parameter. * * @param bool $forceReload * @return \stdClass */ public function getHeaders($forceReload = false) { if ($forceReload || !isset($this->headers)) { // raw headers (since imap_headerinfo doesn't use the unique id) $rawHeaders = $this->getRawHeaders(); // convert raw header string into a usable object $headerObject = imap_rfc822_parse_headers($rawHeaders); // to keep this object as close as possible to the original header object we add the udate property if (isset($headerObject->date)) { $headerObject->udate = strtotime($headerObject->date); } else { $headerObject->date = null; $headerObject->udate = null; } $this->headers = $headerObject; } return $this->headers; }
/** * gets 'from' email from a message * @param int $num the message number * @return string $email_from */ function getMessageFromEmail($num) { $header = imap_rfc822_parse_headers($this->mail->getRawHeader($num)); return $from_email = $header->from[0]->mailbox . "@" . $header->from[0]->host; }
/** * This function returns an object containing the headers of the message. This is done by taking the raw headers * and running them through the imap_rfc822_parse_headers function. The results are only retrieved from the server * once unless passed true as a parameter. * * @param bool $forceReload * @return stdClass */ public function getHeaders($forceReload = false) { if ($forceReload || !isset($this->headers)) { // raw headers (since imap_headerinfo doesn't use the unique id) $rawHeaders = imap_fetchheader($this->imapStream, $this->uid, FT_UID); // convert raw header string into a usable object $headerObject = imap_rfc822_parse_headers($rawHeaders); // to keep this object as close as possible to the original header object we add the udate property $headerObject->udate = strtotime($headerObject->date); $this->headers = $headerObject; } return $this->headers; }
/** * Returns headers. * * @param string $pid Part Id * @return array * @throws \Jyxo\Mail\Parser\EmailNotExistException If no such email exists */ public function getHeaders($pid = null) { // Parses headers $rawHeaders = $this->getRawHeaders($pid); if (null === $pid) { $msgno = imap_msgno($this->connection, $this->uid); if (0 === $msgno) { throw new Parser\EmailNotExistException('Email does not exist'); } $headerInfo = imap_headerinfo($this->connection, $msgno); } else { $headerInfo = imap_rfc822_parse_headers($rawHeaders); } // Adds a header that the IMAP extension does not support if (preg_match("~Disposition-Notification-To:(.+?)(?=\r?\n(?:\\S|\r?\n))~is", $rawHeaders, $matches)) { $addressList = imap_rfc822_parse_adrlist($matches[1], ''); // {''} is used because of CS rules $headerInfo->{'disposition_notification_toaddress'} = substr(trim($matches[1]), 0, 1024); $headerInfo->{'disposition_notification_to'} = array($addressList[0]); } $headers = array(); static $mimeHeaders = array('toaddress', 'ccaddress', 'bccaddress', 'fromaddress', 'reply_toaddress', 'senderaddress', 'return_pathaddress', 'subject', 'fetchfrom', 'fetchsubject', 'disposition_notification_toaddress'); foreach ($headerInfo as $key => $value) { if (!is_object($value) && !is_array($value)) { if (in_array($key, $mimeHeaders)) { $headers[$key] = $this->decodeMimeHeader($value); } else { $headers[$key] = $this->convertToUtf8($value); } } } // Adds "udate" if missing if (!empty($headerInfo->udate)) { $headers['udate'] = $headerInfo->udate; } elseif (!empty($headerInfo->date)) { $headers['udate'] = strtotime($headerInfo->date); } else { $headers['udate'] = time(); } // Parses references $headers['references'] = isset($headers['references']) ? explode('> <', trim($headers['references'], '<>')) : array(); static $types = array('to', 'cc', 'bcc', 'from', 'reply_to', 'sender', 'return_path', 'disposition_notification_to'); for ($i = 0; $i < count($types); $i++) { $type = $types[$i]; $headers[$type] = array(); if (isset($headerInfo->{$type})) { foreach ($headerInfo->{$type} as $object) { $newHeader = array(); foreach ($object as $attributeName => $attributeValue) { if (!empty($attributeValue)) { $newHeader[$attributeName] = 'personal' === $attributeName ? $this->decodeMimeHeader($attributeValue) : $this->convertToUtf8($attributeValue); } } if (!empty($newHeader)) { if (isset($newHeader['mailbox'], $newHeader['host'])) { $newHeader['email'] = $newHeader['mailbox'] . '@' . $newHeader['host']; } elseif (isset($newHeader['mailbox'])) { $newHeader['email'] = $newHeader['mailbox']; } else { $newHeader['email'] = 'undisclosed-recipients'; } $headers[$type][] = $newHeader; } } } } // Adds X-headers if (preg_match_all("~(X(?:[\\-]\\w+)+):(.+?)(?=\r?\n(?:\\S|\r?\n))~is", $rawHeaders, $matches) > 0) { for ($i = 0; $i < count($matches[0]); $i++) { // Converts to the format used by imap_headerinfo() $key = str_replace('-', '_', strtolower($matches[1][$i])); // Removes line endings $value = strtr(trim($matches[2][$i]), array("\r" => '', "\n" => '', "\t" => ' ')); $headers[$key] = $value; } } return $headers; }
/** * Get mail data * * @param $mailId * @param bool $markAsSeen * @return IncomingMail */ public function getMail($mailId, $markAsSeen = true) { $head = imap_rfc822_parse_headers(imap_fetchheader($this->getImapStream(), $mailId, FT_UID)); $mail = new IncomingMail(); $mail->id = $mailId; $mail->date = date('Y-m-d H:i:s', isset($head->date) ? strtotime(preg_replace('/\\(.*?\\)/', '', $head->date)) : time()); $mail->subject = isset($head->subject) ? $this->decodeMimeStr($head->subject, $this->serverEncoding) : null; $mail->fromName = isset($head->from[0]->personal) ? $this->decodeMimeStr($head->from[0]->personal, $this->serverEncoding) : null; $mail->fromAddress = strtolower($head->from[0]->mailbox . '@' . $head->from[0]->host); if (isset($head->to)) { $toStrings = array(); foreach ($head->to as $to) { if (!empty($to->mailbox) && !empty($to->host)) { $toEmail = strtolower($to->mailbox . '@' . $to->host); $toName = isset($to->personal) ? $this->decodeMimeStr($to->personal, $this->serverEncoding) : null; $toStrings[] = $toName ? "{$toName} <{$toEmail}>" : $toEmail; $mail->to[$toEmail] = $toName; } } $mail->toString = implode(', ', $toStrings); } if (isset($head->cc)) { foreach ($head->cc as $cc) { $mail->cc[strtolower($cc->mailbox . '@' . $cc->host)] = isset($cc->personal) ? $this->decodeMimeStr($cc->personal, $this->serverEncoding) : null; } } if (isset($head->reply_to)) { foreach ($head->reply_to as $replyTo) { $mail->replyTo[strtolower($replyTo->mailbox . '@' . $replyTo->host)] = isset($replyTo->personal) ? $this->decodeMimeStr($replyTo->personal, $this->serverEncoding) : null; } } if (isset($head->message_id)) { $mail->messageId = $head->message_id; } $mailStructure = imap_fetchstructure($this->getImapStream(), $mailId, FT_UID); if (empty($mailStructure->parts)) { $this->initMailPart($mail, $mailStructure, 0, $markAsSeen); } else { foreach ($mailStructure->parts as $partNum => $partStructure) { $this->initMailPart($mail, $partStructure, $partNum + 1, $markAsSeen); } } return $mail; }
if(!class_exists('Eden_Mail_Pop3')){class Eden_Mail_Pop3 extends Eden_Class{const TIMEOUT=30;const NO_SUBJECT='(no subject)';protected $_host=NULL;protected $_port=NULL;protected $_ssl=false;protected $_tls=false;protected $_username=NULL;protected $_password=NULL;protected $_timestamp=NULL;protected $_socket=NULL;protected $_loggedin=false;private $_debugging=false;public static function i(){return self::_getMultiple(__CLASS__);}public function __construct($host,$user,$pass,$port=NULL,$ssl=false,$tls=false){Eden_Mail_Error::i()->argument(1,'string')->argument(2,'string')->argument(3,'string')->argument(4,'int','null')->argument(5,'bool')->argument(6,'bool');if (is_null($port)){$port=$ssl ? 995 : 110;}$this->_host=$host;$this->_username=$user;$this->_password=$pass;$this->_port=$port;$this->_ssl=$ssl;$this->_tls=$tls;$this->connect();}public function connect($test=false){Eden_Mail_Error::i()->argument(1,'bool');if($this->_loggedin){return $this;}$host=$this->_host;if ($this->_ssl){$host='ssl://'.$host;}$errno=0;$errstr='';$this->_socket=fsockopen($host,$this->_port,$errno,$errstr,self::TIMEOUT);if (!$this->_socket){Eden_Mail_Error::i()->setMessage(Eden_Mail_Error::SERVER_ERROR)->addVariable($host.':'.$this->_port)->trigger();}$welcome=$this->_receive();strtok($welcome,'<');$this->_timestamp=strtok('>');if (!strpos($this->_timestamp,'@')){$this->_timestamp=null;}else{$this->_timestamp='<'.$this->_timestamp.'>';}if ($this->_tls){$this->_call('STLS');if (!stream_socket_enable_crypto($this->_socket,true,STREAM_CRYPTO_METHOD_TLS_CLIENT)){$this->disconnect();Eden_Mail_Error::i()->setMessage(Eden_Mail_Exception::TLS_ERROR)->addVariable($host.':'.$this->_port)->trigger();}}if($test){$this->disconnect();return $this;}if ($this->_timestamp){try{$this->_call('APOP '.$this->_username.' '.md5($this->_timestamp.$this->_password));return;}catch (Exception $e){}}$this->_call('USER '.$this->_username);$this->_call('PASS '.$this->_password);$this->_loggedin=true;return $this;}public function disconnect(){if (!$this->_socket){return;}try{$this->request('QUIT');}catch (Exception $e){}fclose($this->_socket);$this->_socket=NULL;}public function getEmails($start=0,$range=10){Eden_Mail_Error::i()->argument(1,'int')->argument(2,'int');$total=$this->getEmailTotal();$total=$total['messages'];if($total==0){return array();}if (!is_array($start)){$range=$range > 0 ? $range : 1;$start=$start >=0 ? $start : 0;$max=$total - $start;if($max < 1){$max=$total;}$min=$max - $range + 1;if($min < 1){$min=1;}$set=$min.':'.$max;if($min==$max){$set=$min;}}$emails=array();for($i=$min;$i <=$max;$i++){$emails[]=$this->_getEmailFormat($this->_call('RETR '.$i,true));}return $emails;}public function getEmailTotal(){list($messages,$octets)=explode(' ',$this->_call('STAT'));return $messages;}public function remove($msgno){Eden_Mail_Error::i()->argument(1,'int','string');$this->_call("DELE $msgno");if(!$this->_loggedin || !$this->_socket){return false;}if(!is_array($msgno)){$msgno=array($msgno);}foreach($msgno as $number){$this->_call('DELE '.$number);}return $this;}protected function _call($command,$multiline=false){if(!$this->_send($command)){return false;}return $this->_receive($multiline);}protected function _receive($multiline=false){$result=@fgets($this->_socket);$status=$result=trim($result);$message='';if (strpos($result,' ')){list($status,$message)=explode(' ',$result,2);}if ($status !='+OK'){return false;}if ($multiline){$message='';$line=fgets($this->_socket);while ($line && rtrim($line,"\r\n") !='.'){if ($line[0]=='.'){$line=substr($line,1);}$this->_debug('Receiving: '.$line);$message.=$line;$line=fgets($this->_socket);};}return $message;}protected function _send($command){$this->_debug('Sending: '.$command);return fputs($this->_socket,$command."\r\n");}private function _debug($string){if($this->_debugging){$string=htmlspecialchars($string);echo '<pre>'.$string.'</pre>'."\n";}return $this;}private function _getEmailFormat($email,array $flags=array()){if(is_array($email)){$email=implode("\n",$email);}$parts=preg_split("/\n\s*\n/",$email,2);$head=$parts[0];$body=NULL;if(isset($parts[1]) && trim($parts[1]) !=')'){$body=$parts[1];}$lines=explode("\n",$head);$head=array();foreach($lines as $line){if(trim($line) && preg_match("/^\s+/",$line)){$head[count($head)-1].=' '.trim($line);continue;}$head[]=trim($line);}$head=implode("\n",$head);$recipientsTo=$recipientsCc=$recipientsBcc=$sender=array();$headers1=imap_rfc822_parse_headers($head);$headers2=$this->_getHeaders($head);$sender['name']=NULL;if(isset($headers1->from[0]->personal)){$sender['name']=$headers1->from[0]->personal;if(preg_match("/^\=\?[a-zA-Z]+\-[0-9]+.*\?/",strtolower($sender['name']))){$sender['name']=str_replace('_',' ',mb_decode_mimeheader($sender['name']));}}$sender['email']=$headers1->from[0]->mailbox.'@'.$headers1->from[0]->host;if(isset($headers1->to)){foreach($headers1->to as $to){if(!isset($to->mailbox,$to->host)){continue;}$recipient=array('name'=>NULL);if(isset($to->personal)){$recipient['name']=$to->personal;if(preg_match("/^\=\?[a-zA-Z]+\-[0-9]+.*\?/",strtolower($recipient['name']))){$recipient['name']=str_replace('_',' ',mb_decode_mimeheader($recipient['name']));}}$recipient['email']=$to->mailbox.'@'.$to->host;$recipientsTo[]=$recipient;}}if(isset($headers1->cc)){foreach($headers1->cc as $cc){$recipient=array('name'=>NULL);if(isset($cc->personal)){$recipient['name']=$cc->personal;if(preg_match("/^\=\?[a-zA-Z]+\-[0-9]+.*\?/",strtolower($recipient['name']))){$recipient['name']=str_replace('_',' ',mb_decode_mimeheader($recipient['name']));}}$recipient['email']=$cc->mailbox.'@'.$cc->host;$recipientsCc[]=$recipient;}}if(isset($headers1->bcc)){foreach($headers1->bcc as $bcc){$recipient=array('name'=>NULL);if(isset($bcc->personal)){$recipient['name']=$bcc->personal;if(preg_match("/^\=\?[a-zA-Z]+\-[0-9]+.*\?/",strtolower($recipient['name']))){$recipient['name']=str_replace('_',' ',mb_decode_mimeheader($recipient['name']));}}$recipient['email']=$bcc->mailbox.'@'.$bcc->host;$recipientsBcc[]=$recipient;}}if(!isset( $headers1->subject ) || strlen(trim($headers1->subject))===0){$headers1->subject=self::NO_SUBJECT;}$headers1->subject=str_replace(array('<','>'),'',trim($headers1->subject));if(preg_match("/^\=\?[a-zA-Z]+\-[0-9]+.*\?/",strtolower($headers1->subject))){$headers1->subject=str_replace('_',' ',mb_decode_mimeheader($headers1->subject));}$topic=isset($headers2['thread-topic']) ? $headers2['thread-topic'] : $headers1->subject;$parent=isset($headers2['in-reply-to']) ? str_replace('"','',$headers2['in-reply-to']) : NULL;$date=isset($headers1->date) ? strtotime($headers1->date) : NULL;if(isset($headers2['message-id'])){$messageId=str_replace('"','',$headers2['message-id']);}else{$messageId='<eden-no-id-'.md5(uniqid()).'>';}$attachment=isset($headers2['content-type']) && strpos($headers2['content-type'],'multipart/mixed')===0;$format=array( 'id'=>$messageId,'parent'=>$parent,'topic'=>$topic,'mailbox'=>'INBOX','date'=>$date,'subject'=>str_replace('’','\'',$headers1->subject),'from'=>$sender,'flags'=>$flags,'to'=>$recipientsTo,'cc'=>$recipientsCc,'bcc'=>$recipientsBcc,'attachment'=>$attachment);if(trim($body) && $body !=')'){$parts=$this->_getParts($email);if(empty($parts)){$parts=array('text/plain'=>$body);}$body=$parts;$attachment=array();if(isset($body['attachment'])){$attachment=$body['attachment'];unset($body['attachment']);}$format['body']=$body;$format['attachment']=$attachment;}return $format;}private function _getHeaders($rawData){if(is_string($rawData)){$rawData=explode("\n",$rawData);}$key=NULL;$headers=array();foreach($rawData as $line){$line=trim($line);if(preg_match("/^([a-zA-Z0-9-]+):/i",$line,$matches)){$key=strtolower($matches[1]);if(isset($headers[$key])){if(!is_array($headers[$key])){$headers[$key]=array($headers[$key]);}$headers[$key][]=trim(str_replace($matches[0],'',$line));continue;}$headers[$key]=trim(str_replace($matches[0],'',$line));continue;}if(!is_null($key) && isset($headers[$key])){if(is_array($headers[$key])){$headers[$key][count($headers[$key])-1].=' '.$line;continue;}$headers[$key].=' '.$line;}}return $headers;}private function _getParts($content,array $parts=array()){list($head,$body)=preg_split("/\n\s*\n/",$content,2);$head=$this->_getHeaders($head);if(!isset($head['content-type'])){return $parts;}if(is_array($head['content-type'])){$type=array($head['content-type'][1]);if(strpos($type[0],';') !==false){$type=explode(';',$type[0],2);}}else{$type=explode(';',$head['content-type'],2);}$extra=array();if(count($type)==2){$extra=explode(';',str_replace(array('"',"'"),'',trim($type[1])));}$type=trim($type[0]);foreach($extra as $i=>$attr){$attr=explode('=',$attr,2);if(count($attr) > 1){list($key,$value)=$attr;$extra[$key]=$value;}unset($extra[$i]);}if(isset($extra['boundary'])){$sections=explode('--'.str_replace(array('"',"'"),'',$extra['boundary']),$body);array_pop($sections);array_shift($sections);foreach($sections as $section){$parts=$this->_getParts($section,$parts);}}else{if(isset($head['content-transfer-encoding'])){switch(strtolower($head['content-transfer-encoding'])){case 'binary': $body=imap_binary($body);case 'base64': $body=base64_decode($body);break;case 'quoted-printable': $body=quoted_printable_decode($body);break;case '7bit': $body=mb_convert_encoding ($body,'UTF-8','ISO-2022-JP');break;default: $body=str_replace(array("\n",' '),'',$body);break;}}if(isset($extra['name'])){$parts['attachment'][$extra['name']][$type]=$body;}else{$parts[$type]=$body;}}return $parts;}}}