/** * Method to read email from imap extension and return Zend Mail Message object. * * This is bridge while migrating to Zend Mail package supporting reading from imap extension functions. * * @param resource $mbox * @param integer $num * @param array $info connection information about connection * @return ImapMessage */ public static function createFromImap($mbox, $num, $info) { // check if the current message was already seen list($overview) = imap_fetch_overview($mbox, $num); $headers = imap_fetchheader($mbox, $num); $content = imap_body($mbox, $num); // fill with "\Seen", "\Deleted", "\Answered", ... etc $knownFlags = array('recent' => Zend\Mail\Storage::FLAG_RECENT, 'flagged' => Zend\Mail\Storage::FLAG_FLAGGED, 'answered' => Zend\Mail\Storage::FLAG_ANSWERED, 'deleted' => Zend\Mail\Storage::FLAG_DELETED, 'seen' => Zend\Mail\Storage::FLAG_SEEN, 'draft' => Zend\Mail\Storage::FLAG_DRAFT); $flags = array(); foreach ($knownFlags as $flag => $value) { if ($overview->{$flag}) { $flags[] = $value; } } $message = new self(array('root' => true, 'headers' => $headers, 'content' => $content, 'flags' => $flags)); // set MailDate to $message object, as it's not available in message headers, only in IMAP itself // this likely "message received date" $imapheaders = imap_headerinfo($mbox, $num); $header = new GenericHeader('X-IMAP-UnixDate', $imapheaders->udate); $message->getHeaders()->addHeader($header); $message->mbox = $mbox; $message->num = $num; $message->info = $info; return $message; }
/** * Recupera o conteúdo de uma mensagem * @param MailContext $context Contexto da conexão * @param Message $message * @return Message A própria mensagem * @throws MailStateException Caso o estado do objeto não implemente abertura * @throws MailException Caso não seja possível recuperar o conteúdo da mensagem */ public function fetch( MailContext $context , Message $message ) { $msgNum = imap_msgno( ImapState::$resource , $message->getUID() ); $structure = imap_fetchstructure( ImapState::$resource , $msgNum ); $overview = (array) current( imap_fetch_overview( ImapState::$resource , $msgNum ) ); $message->setHeaders( imap_fetchheader( ImapState::$resource , $msgNum ) ); $message->setOverview( $overview ); if ( isset( $structure->parts ) && count( $structure->parts ) ) { foreach ( $structure->parts as $key => $part ) { $this->fetchContent( $message , $part->subtype , $msgNum , $key + 1 ); } } else { $this->fetchContent( $message , $structure->subtype , $msgNum , 1 ); } }
/** * 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 retrieve_message($auth_user, $accountid, $messageid, $fullheaders) { $message = array(); if (!($auth_user && $messageid && $accountid)) { return false; } $imap = open_mailbox($auth_user, $accountid); if (!$imap) { return false; } $header = imap_header($imap, $messageid); if (!$header) { return false; } $message['body'] = imap_body($imap, $messageid); if (!$message['body']) { $message['body'] = "[This message has no body]\n\n\n\n\n\n"; } if ($fullheaders) { $message['fullheaders'] = imap_fetchheader($imap, $messageid); } else { $message['fullheaders'] = ''; } $message['subject'] = $header->subject; $message['fromaddress'] = $header->fromaddress; $message['toaddress'] = $header->toaddress; $message['ccaddress'] = $header->ccaddress; $message['date'] = $header->date; // note we can get more detailed information by using from and to // rather than fromaddress and toaddress, but these are easier imap_close($imap); return $message; }
function get_message($uid) { $raw_header = imap_fetchheader($this->stream, $uid, FT_UID); $raw_body = imap_body($this->stream, $uid, FT_UID); $message = new Email_Parser($raw_header . $raw_body); return $message; }
function get_message($msg) { $header = imap_fetchheader($this->_connection, $msg); echo "<h1>header {$msg}:</h1><br>".$header; $message = imap_body($this->_connection, $msg); echo "<h1>message {$msg}:</h1><br>".$message; return $header.$message; }
function fetch_raw_mail($stream, $msg_num, $flags = 0) { $flags |= FT_PREFETCHTEXT; // do we force use of msg UID's if ($this->force_msg_uids == True && !($flags & FT_UID)) { $flags |= FT_UID; } return imap_fetchheader($stream, $msg_num, $flags); }
/** * @param $mailId * @return object */ public function getImapHeaderInfo($mailId) { $imapHeader = imap_fetchheader($this->getImapStream(), $mailId, FT_UID); $parsed = array(); $blocks = preg_split('/\\n\\n/', $imapHeader); $matches = array(); foreach ($blocks as $i => $block) { $parsed[$i] = array(); $lines = preg_split('/\\n(([\\w.-]+)\\: *((.*\\n\\s+.+)+|(.*(?:\\n))|(.*))?)/', $block, -1, PREG_SPLIT_DELIM_CAPTURE); foreach ($lines as $line) { if (preg_match('/^\\n?([\\w.-]+)\\: *((.*\\n\\s+.+)+|(.*(?:\\n))|(.*))?$/', $line, $matches)) { $parsed[$i][$matches[1]] = preg_replace('/\\n +/', ' ', trim($matches[2])); } } } return $parsed; }
/** * Cabesera de mensage * * @param int $numMsg * @return array */ public function headerMsg($numMsg, $uid = false) { //$numMsg es el uid y no el numero de secuencia if ($uid) { $numMsg = imap_msgno($this->connect, $numMsg); } $header = explode("\n", imap_fetchheader($this->connect, $numMsg)); if (is_array($header) && count($header)) { $head = array(); foreach ($header as $line) { // separate name and value eregi("^([^:]*): (.*)", $line, $arg); $head[$arg[1]] = $arg[2]; } } return $head; }
static function fetch($options) { if ($mbox = imap_open(sprintf('{%1$s:%2$s/%3$s}INBOX', $options['server'], $options['port'], implode('/', $options['settings'])), $options['user'], $options['pass'])) { $ret = array(); if (($messages = imap_num_msg($mbox)) > 0) { for ($message = 1; $message < $messages + 1; $message++) { $eml = imap_fetchheader($mbox, $message) . imap_body($mbox, $message); $data = array('Task' => array()); $email_data = LilTasksParseEmail::__parseEmailHeader($mbox, $message); $data['Task']['title'] = $email_data['subject']; $data['Task']['happened'] = strftime('%Y-%m-%d', strtotime($email_data['date'])); list($sender, $domain) = explode('@', $email_data['from']); if ($sender == 'today') { $data['Task']['deadline'] = strftime('%Y-%m-%d'); } else { if ($sender == 'tomorrow') { $data['Task']['deadline'] = strftime('%Y-%m-%d', time() + 24 * 60 * 60); } else { if (in_array(strtolower($sender), array('monday', 'tuesday', 'wednesday', 'thursday', 'saturday', 'sunday'))) { $data['Task']['deadline'] = strftime('%Y-%m-%d', strtotime('next ' . ucfirst($sender))); } } } $hash = sha1($data['Task']['happened'] . '_' . $email_data['subject']); $parts = array(); $data['Task']['descript'] = LilTasksParseEmail::__parseEmailBody($mbox, $message, $hash, $parts); file_put_contents(TMP . $hash . '.eml', $eml); $data['Attachment'][0] = array('model' => 'Task', 'filename' => array('name' => $hash . '.eml', 'tmp_name' => TMP . $hash . '.eml'), 'title' => 'SOURCE: ' . $data['Task']['title']); App::uses('Sanitize', 'Utility'); foreach ($parts as $part) { if (!empty($part['attachment'])) { $data['Attachment'][] = array('model' => 'Task', 'filename' => array('name' => Sanitize::paranoid($part['attachment']['filename']), 'tmp_name' => $part['attachment']['tmp']), 'title' => $part['attachment']['filename']); } } $ret[$message] = $data; imap_delete($mbox, $message); } } return $ret; imap_close($mbox, CL_EXPUNGE); } else { var_dump(imap_errors()); } }
function email_msg_headers($mbox, $uid) { $raw_header = $mbox && $uid ? @imap_fetchheader($mbox, $uid, FT_UID) : ''; $raw_header = str_replace("\r", '', $raw_header); $ret = array(); $h = split("\n", $raw_header); if (count($h)) { foreach ($h as $line) { if (preg_match("/^[a-zA-Z]/", $line)) { $key = substr($line, 0, strpos($line, ':')); $value = substr($line, strpos($line, ':') + 1); $last_entry = strtolower($key); $ret[$last_entry] = trim($value); } else { $ret[$last_entry] .= ' ' . trim($line); } } } return $ret; }
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; }
function imap_get_url($u) { if (!($c = imap_open_url($u))) { return FALSE; } extract(parse_url($u)); extract(imap_parse_path($path)); if ($mailbox) { if ($uid) { $msgno = imap_msgno($c, $uid); $o = imap_fetchstructure($c, $msgno); } else { $o = array(); $n = imap_num_msg($c); while ($i++ < $n) { $o[] = imap_fetchheader($c, $i); } } } else { $o = imap_list($c, '{}', '*'); } return $o; }
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); } }
ob_start(); $mbox = @imap_open($_email['server'], $_email['username'], $_email['password']); if (!$mbox) { ob_end_clean(); sleep(10); continue; } $processed = 0; $msgs = @imap_search($mbox, 'UNSEEN'); if ($msgs) { foreach ($msgs as $msgid) { // Crap out here if we've run out of time if (time() >= $endtime) { break; } $imap_headers = @imap_fetchheader($mbox, $msgid); if (!$imap_headers) { break; } $headers = array(); foreach (explode("\n", trim($imap_headers)) as $header) { if (strlen(trim($header)) == 0 or $header[0] == ' ' or $header[0] == "\t") { continue; } list($key, $val) = explode(':', trim($header)); $key = strtolower($key); $val = trim($val); switch ($key) { case 'x-twitterrecipientscreenname': if ($val != $_twitter['username']) { // Skip to the next message - this one is not for us!
<body> <?php mysql_connect('localhost', 'kamas3_emailsc', 'bingo45'); mysql_select_db('kamas3_emailsc'); $user = '******'; $pass = '******'; $imap_server = "{192.254.214.105:143/imap/notls}INBOX"; // Connect to the pop3 email inbox belonging to $user // If you need SSL remove the novalidate-cert section $mbox = imap_open($imap_server, $user, $pass); $MC = imap_check($mbox); $sorted_mbox = imap_sort($mbox, SORTDATE, 1); $totalrows = imap_num_msg($mbox); $startvalue = 0; while ($startvalue < $totalrows && $startvalue < 100) { $headers = imap_fetchheader($mbox, $sorted_mbox[$startvalue]); // echo $headers; // echo htmlentities($headers->message_id); $subject = array(); preg_match_all('/^Subject: (.*)/m', $headers, $subject); // print $subject[1][0] . "<br />"; $subject = isset($subject[1][0]) ? $subject[1][0] : (isset($subject[0][0]) ? $subject[0][0] : ''); if (strpos(strtolower($subject), 'enquiry for you at') !== FALSE) { $msg = imap_fetchbody($mbox, $sorted_mbox[$startvalue], 2); // echo $msg.'</br>'; $msg_array = explode('<tr', $msg); echo count($msg_array) . " "; if (count($msg_array) < 5) { $msg_array = explode('<TR', $msg); //echo count($msg_array)." "; }
/** * get the basic details like sender and reciver with flags like attatchments etc * * @param int $uid the number of the message * @return array empty on error/nothing or array of formatted details */ protected function _getFormattedMail($Model, $uid, $fetchAttachments = false) { // Translate uid to msg_no. Has no decent fail $msg_number = imap_msgno($this->Stream, $uid); // A hack to detect if imap_msgno failed, and we're in fact looking at the wrong mail if ($uid != ($mailuid = imap_uid($this->Stream, $msg_number))) { pr(compact('Mail')); return $this->err($Model, 'Mail id mismatch. parameter id: %s vs mail id: %s', $uid, $mailuid); } // Get Mail with a property: 'date' or fail if (!($Mail = imap_headerinfo($this->Stream, $msg_number)) || !property_exists($Mail, 'date')) { pr(compact('Mail')); return $this->err($Model, 'Unable to find mail date property in Mail corresponding with uid: %s. Something must be wrong', $uid); } // Get Mail with a property: 'type' or fail if (!($flatStructure = $this->_flatStructure($Model, $uid))) { return $this->err($Model, 'Unable to find structure type property in Mail corresponding with uid: %s. Something must be wrong', $uid); } $plain = $this->_fetchFirstByMime($flatStructure, 'text/plain'); $html = $this->_fetchFirstByMime($flatStructure, 'text/html'); $return[$Model->alias] = array('id' => $this->_toId($uid), 'message_id' => $Mail->message_id, 'email_number' => $Mail->Msgno, 'to' => $this->_personId($Mail, 'to', 'address'), 'to_name' => $this->_personId($Mail, 'to', 'name'), 'from' => $this->_personId($Mail, 'from', 'address'), 'from_name' => $this->_personId($Mail, 'from', 'name'), 'reply_to' => $this->_personId($Mail, 'reply_to', 'address'), 'reply_to_name' => $this->_personId($Mail, 'reply_to', 'name'), 'sender' => $this->_personId($Mail, 'sender', 'address'), 'sender_name' => $this->_personId($Mail, 'sender', 'name'), 'subject' => htmlspecialchars(@$Mail->subject), 'slug' => Inflector::slug(@$Mail->subject, '-'), 'header' => @imap_fetchheader($this->Stream, $uid, FT_UID), 'body' => $html, 'plainmsg' => $plain ? $plain : $html, 'size' => @$Mail->Size, 'recent' => @$Mail->Recent === 'R' ? 1 : 0, 'seen' => @$Mail->Unseen === 'U' ? 0 : 1, 'flagged' => @$Mail->Flagged === 'F' ? 1 : 0, 'answered' => @$Mail->Answered === 'A' ? 1 : 0, 'draft' => @$Mail->Draft === 'X' ? 1 : 0, 'deleted' => @$Mail->Deleted === 'D' ? 1 : 0, 'thread_count' => $this->_getThreadCount($Mail), 'in_reply_to' => @$Mail->in_reply_to, 'reference' => @$Mail->references, 'new' => (int) @$Mail->in_reply_to, 'created' => date('Y-m-d H:i:s', strtotime($Mail->date))); if ($fetchAttachments) { $return['Attachment'] = $this->_fetchAttachments($flatStructure, $Model); } // Auto mark after read if (!empty($this->config['auto_mark_as'])) { $marks = '\\' . join(' \\', $this->config['auto_mark_as']); if (!imap_setflag_full($this->Stream, $uid, $marks, ST_UID)) { $this->err($Model, 'Unable to mark email %s as %s', $uid, $marks); } } return $return; }
public function fetchHeader() { return imap_fetchheader($this->connection, $this->message_id); }
protected function check_mailbox() { imap_ping($this->conn); $count = imap_num_msg($this->conn); common_log(LOG_INFO, "Found {$count} messages"); if ($count > 0) { $handler = new IMAPMailHandler(); for ($i = 1; $i <= $count; $i++) { $rawmessage = imap_fetchheader($this->conn, $count, FT_PREFETCHTEXT) . imap_body($this->conn, $i); $handler->handle_message($rawmessage); imap_delete($this->conn, $i); } imap_expunge($this->conn); common_log(LOG_INFO, "Finished processing messages"); } return $count; }
/** * 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; }
public function getMessage($message) { return imap_fetchheader($this->conn, $message, FT_PREFETCHTEXT); }
function getHeader($mid) { return imap_fetchheader($this->mbox, $mid, FT_PREFETCHTEXT); }
$imap = imap_open($mailboxRoot . $boxName, $mailUsername, $mailPassword) or die("Can't open {$boxName} box! " . imap_last_error()); $added = 0; $num_msg = imap_num_msg($imap); //if ($num_msg > 40) $num_msg = 40; // go through each message for ($i = 1; $i <= $num_msg; $i++) { $thisUID = imap_uid($imap, $i); $result = mysql_query("SELECT * FROM winamp_emails WHERE uid = '{$thisUID}'"); if (mysql_num_rows($result) == 0) { $header = imap_headerinfo($imap, $i); $thisTo = addslashes($header->toaddress); $thisCC = addslashes($header->ccaddress); $thisFrom = addslashes($header->fromaddress); $thisSubject = addslashes($header->subject); $thisDate = strtotime($header->date); $thisHeader = addslashes(imap_fetchheader($imap, $i)); mysql_query("INSERT INTO winamp_emails (uid, mailbox, fromaddress, toaddress, ccaddress, subject, date, headers) \n\t\t\t\t\t\t\t\t\t\t\tVALUES ('{$thisUID}', '{$boxName}', '{$thisFrom}', '{$thisTo}', '{$thisCC}', '{$thisSubject}', FROM_UNIXTIME({$thisDate}), '{$thisHeader}')"); if (mysql_error()) { die(mysql_error()); } $email_id = mysql_insert_id(); $added++; $total_added++; //$thisBody = imap_body($imap, $i, FT_PEEK); $thisStructure = imap_fetchstructure($imap, $i); $thisType = $thisStructure->type; $thisSubType = $thisStructure->subtype; insertBodyPart($imap, $i, $thisStructure, $email_id); } } $netTime = time() - $startTime;
/** * 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; }
function run() { $logger = DevblocksPlatform::getConsoleLog(); $logger->info("[POP3] Starting POP3 Task"); if (!extension_loaded("imap")) { die("IMAP Extension not loaded!"); } @set_time_limit(0); // Unlimited (if possible) @ini_set('memory_limit', '64M'); $accounts = DAO_Mail::getPop3Accounts(); /* @var $accounts CerberusPop3Account[] */ $timeout = ini_get('max_execution_time'); // Allow runtime overloads (by host, etc.) @($gpc_pop3_max = DevblocksPlatform::importGPC($_REQUEST['pop3_max'], 'integer')); $max_downloads = !empty($gpc_pop3_max) ? $gpc_pop3_max : $this->getParam('max_messages', $timeout ? 20 : 50); // [JAS]: Make sure our output directory is writeable if (!is_writable(APP_MAIL_PATH . 'new' . DIRECTORY_SEPARATOR)) { $logger->err("[POP3] The mail storage directory is not writeable. Skipping POP3 download."); return; } foreach ($accounts as $account) { /* @var $account CerberusPop3Account */ if (!$account->enabled) { continue; } $logger->info('[POP3] Account being parsed is ' . $account->nickname); switch ($account->protocol) { default: case 'pop3': // 110 $connect = sprintf("{%s:%d/pop3/notls}INBOX", $account->host, $account->port); break; case 'pop3-ssl': // 995 $connect = sprintf("{%s:%d/pop3/ssl/novalidate-cert}INBOX", $account->host, $account->port); break; case 'imap': // 143 $connect = sprintf("{%s:%d/notls}INBOX", $account->host, $account->port); break; case 'imap-ssl': // 993 $connect = sprintf("{%s:%d/imap/ssl/novalidate-cert}INBOX", $account->host, $account->port); break; } $runtime = microtime(true); if (false === ($mailbox = @imap_open($connect, !empty($account->username) ? $account->username : "", !empty($account->password) ? $account->password : ""))) { $logger->err("[POP3] Failed with error: " . imap_last_error()); continue; } $messages = array(); $check = imap_check($mailbox); // [TODO] Make this an account setting? $total = min($max_downloads, $check->Nmsgs); $logger->info('[POP3] Init time: ' . (microtime(true) - $runtime) * 1000, " ms"); $runtime = microtime(true); for ($i = 1; $i <= $total; $i++) { /* * [TODO] Logic for max message size (>1MB, etc.) handling. If over a * threshold then use the attachment parser (imap_fetchstructure) to toss * non-plaintext until the message fits. */ $msgno = $i; $time = microtime(true); $headers = imap_fetchheader($mailbox, $msgno); $body = imap_body($mailbox, $msgno); do { $unique = sprintf("%s.%04d", time(), mt_rand(0, 9999)); $filename = APP_MAIL_PATH . 'new' . DIRECTORY_SEPARATOR . $unique; } while (file_exists($filename)); $fp = fopen($filename, 'w'); if ($fp) { fwrite($fp, $headers, strlen($headers)); fwrite($fp, "\r\n\r\n"); fwrite($fp, $body, strlen($body)); @fclose($fp); } /* * [JAS]: We don't add the .msg extension until we're done with the file, * since this will safely be ignored by the parser until we're ready * for it. */ rename($filename, dirname($filename) . DIRECTORY_SEPARATOR . basename($filename) . '.msg'); unset($headers); unset($body); $time = microtime(true) - $time; $logger->info("[POP3] Downloaded message " . $msgno . " (" . sprintf("%d", $time * 1000) . " ms)"); imap_delete($mailbox, $msgno); continue; } imap_expunge($mailbox); imap_close($mailbox); imap_errors(); $logger->info("[POP3] Total Runtime: " . (microtime(true) - $runtime) * 1000 . " ms"); } }
/** * @param $mid **/ function getAdditionnalHeaders($mid) { $head = array(); $header = explode("\n", imap_fetchheader($this->marubox, $mid)); if (is_array($header) && count($header)) { foreach ($header as $line) { // is line with additional header? if (preg_match("/^X-/i", $line) || preg_match("/^Auto-Submitted/i", $line) || preg_match("/^Received/i", $line)) { // separate name and value if (preg_match("/^([^:]*): (.*)/i", $line, $arg)) { $key = Toolbox::strtolower($arg[1]); if (!isset($head[$key])) { $head[$key] = ''; } else { $head[$key] .= "\n"; } $head[$key] .= trim($arg[2]); } } } } return $head; }
public static function get_mail_detail($mbox, $id, $msgno = false) { $return = array(); if (!$msgno) { $msgno = imap_msgno($mbox, $id); } if (!$id) { $id = imap_uid($mbox, $msgno); } if (!$msgno) { return false; } $header = imap_header($mbox, $msgno); $structure = self::_get_body_attach($mbox, $id, $msgno); $return['id'] = $id; $return['Msgno'] = $header->Msgno; $return['message_id'] = $header->message_id; $return['toaddress'] = self::get_only_email($header->to); $return['fromaddress'] = self::get_only_email($header->from); $return['reply_toaddress'] = self::get_only_email($header->reply_to); $return['ccaddress'] = self::get_only_email($header->cc); $return['bccaddress'] = self::get_only_email($header->bcc); $return['senderaddress'] = self::get_only_email($header->sender); $return['subject'] = self::_decode_text($header->subject); $return['MailDate'] = $header->MailDate; $return['date'] = $header->date; $return['udate'] = $header->udate; $return['udate_formated'] = date("Y-m-d H:i:s", $header->udate); $return['Recent'] = $header->Recent; $return['Unseen'] = $header->Unseen; $return['Flagged'] = $header->Flagged; $return['Answered'] = $header->Answered; $return['Deleted'] = $header->Deleted; $return['Draft'] = $header->Draft; $return['Size'] = $header->Size; $return['body'] = $structure['body']; $return['attachments'] = $structure['attachment']; $return['clean'] = ''; $msgs = imap_fetch_overview($mbox, $msgno); foreach ($msgs as $msg) { $return['clean'] .= imap_fetchheader($mbox, $msg->msgno); } return $return; }
/** Parse messages sitting in mailbox */ function parse_messages() { if ($this->num_msgs > 0) { for ($x = 1; $x < $this->num_msgs + 1; $x++) { # Retrieve raw mail body $rawdata = imap_fetchheader($this->conn, $x) . imap_body($this->conn, $x); # Retrieve mail structure $struct = imap_fetchstructure($this->conn, $x); # Retrieve mail headers $headers = imap_headerinfo($this->conn, $x); # Build array of addresses mail was sent to $to = array(); foreach ($headers->to as $item) { array_push($to, $item->mailbox . "@" . $item->host); } # Get the address message is from $from = $headers->from[0]->mailbox . "@" . $headers->from[0]->host; # FIXME - attachment handling: # Use of dparameters seems to be wrong - the correct key is 'filename' I guess. # More info http://php.net/manual/en/function.imap-fetchstructure.php # Anyway, I have removed the attachment code since it doesn't work AND # the code in the parser script already handle the attachments. # Check if this is a multipart message. (can not use type since # it is 0 for text (.txt) attachments.) // if ($struct->type == 1) { if ($struct->parts) { foreach ($struct->parts as $key => $part) { // Skipping HTML if ($part->ifsubtype == 1 and $part->subtype == "HTML") { continue; } // Ignoring all attachements if (strtolower($part->disposition) != "attachment") { # Retrieve mail body $body = imap_fetchbody($this->conn, $x, $key + 1); # Check for base64 or quoted printable encoding if ($part->encoding == 3) { $body = imap_base64($body); } else { if ($part->encoding == 4) { $body = imap_qprint($body); } } } } } else { # Retrieve mail body (for this single part message). $body = imap_body($this->conn, $x); # Check for base64 or quoted printable encoding if ($struct->encoding == 3) { $body = imap_base64($body); } else { if ($struct->encoding == 4) { $body = imap_qprint($body); } } } # Add message to array $this->messages[] = array('msgno' => $x, 'from' => $from, 'to' => $to, 'message_id' => $headers->message_id, 'subject' => $headers->subject, 'body' => $body, 'rawdata' => $rawdata); } } }
/** * Gets the raw email message from the server * @return string */ function fetchEmail($index) { $header_info = imap_headerinfo($this->_connection, $index); if (IsDebugMode() || $header_info->Recent == 'N' || $header_info->Unseen == 'U') { $email = imap_fetchheader($this->_connection, $index); $email .= imap_body($this->_connection, $index); return $email; } else { return 'already read'; } }
/** * shiny new importOneEmail() method * @param int msgNo * @param bool forDisplay * @param clean_email boolean, default true, */ function importOneEmail($msgNo, $uid, $forDisplay = false, $clean_email = true) { $GLOBALS['log']->debug("InboundEmail processing 1 email {$msgNo}-----------------------------------------------------------------------------------------"); global $timedate; global $app_strings; global $app_list_strings; global $sugar_config; global $current_user; // Bug # 45477 // So, on older versions of PHP (PHP VERSION < 5.3), // calling imap_headerinfo and imap_fetchheader can cause a buffer overflow for exteremly large headers, // This leads to the remaining messages not being read because Sugar crashes everytime it tries to read the headers. // The workaround is to mark a message as read before making trying to read the header of the msg in question // This forces this message not be read again, and we can continue processing remaining msgs. // UNCOMMENT THIS IF YOU HAVE THIS PROBLEM! See notes on Bug # 45477 // $this->markEmails($uid, "read"); $header = imap_headerinfo($this->conn, $msgNo); $fullHeader = imap_fetchheader($this->conn, $msgNo); // raw headers // reset inline images cache $this->inlineImages = array(); // handle messages deleted on server if (empty($header)) { if (!isset($this->email) || empty($this->email)) { $this->email = new Email(); } $q = ""; if ($this->isPop3Protocol()) { $this->email->name = $app_strings['LBL_EMAIL_ERROR_MESSAGE_DELETED']; $q = "DELETE FROM email_cache WHERE message_id = '{$uid}' AND ie_id = '{$this->id}' AND mbox = '{$this->mailbox}'"; } else { $this->email->name = $app_strings['LBL_EMAIL_ERROR_IMAP_MESSAGE_DELETED']; $q = "DELETE FROM email_cache WHERE imap_uid = {$uid} AND ie_id = '{$this->id}' AND mbox = '{$this->mailbox}'"; } // else // delete local cache $r = $this->db->query($q); $this->email->date_sent = $timedate->nowDb(); return false; //return "Message deleted from server."; } /////////////////////////////////////////////////////////////////////// //// DUPLICATE CHECK $dupeCheckResult = $this->importDupeCheck($header->message_id, $header, $fullHeader); if ($forDisplay || $dupeCheckResult) { $GLOBALS['log']->debug('*********** NO duplicate found, continuing with processing.'); $structure = imap_fetchstructure($this->conn, $msgNo); // map of email /////////////////////////////////////////////////////////////////// //// CREATE SEED EMAIL OBJECT $email = new Email(); $email->isDuplicate = $dupeCheckResult ? false : true; $email->mailbox_id = $this->id; $message = array(); $email->id = create_guid(); $email->new_with_id = true; //forcing a GUID here to prevent double saves. //// END CREATE SEED EMAIL /////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////// //// PREP SYSTEM USER if (empty($current_user)) { // I-E runs as admin, get admin prefs $current_user = new User(); $current_user->getSystemUser(); } $tPref = $current_user->getUserDateTimePreferences(); //// END USER PREP /////////////////////////////////////////////////////////////////// if (!empty($header->date)) { $unixHeaderDate = $timedate->fromString($header->date); } /////////////////////////////////////////////////////////////////// //// HANDLE EMAIL ATTACHEMENTS OR HTML TEXT //// Inline images require that I-E handle attachments before body text // parts defines attachments - be mindful of .html being interpreted as an attachment if ($structure->type == 1 && !empty($structure->parts)) { $GLOBALS['log']->debug('InboundEmail found multipart email - saving attachments if found.'); $this->saveAttachments($msgNo, $structure->parts, $email->id, 0, $forDisplay); } elseif ($structure->type == 0) { $uuemail = $this->isUuencode($email->description) ? true : false; /* * UUEncoded attachments - legacy, but still have to deal with it * format: * begin 777 filename.txt * UUENCODE * * end */ // set body to the filtered one if ($uuemail) { $email->description = $this->handleUUEncodedEmailBody($email->description, $email->id); $email->retrieve($email->id); $email->save(); } } else { if ($this->port != 110) { $GLOBALS['log']->debug('InboundEmail found a multi-part email (id:' . $msgNo . ') with no child parts to parse.'); } } //// END HANDLE EMAIL ATTACHEMENTS OR HTML TEXT /////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////// //// ASSIGN APPROPRIATE ATTRIBUTES TO NEW EMAIL OBJECT // handle UTF-8/charset encoding in the ***headers*** global $db; $email->name = $this->handleMimeHeaderDecode($header->subject); $email->date_start = !empty($unixHeaderDate) ? $timedate->asUserDate($unixHeaderDate) : ""; $email->time_start = !empty($unixHeaderDate) ? $timedate->asUserTime($unixHeaderDate) : ""; $email->type = 'inbound'; $email->date_created = !empty($unixHeaderDate) ? $timedate->asUser($unixHeaderDate) : ""; $email->status = 'unread'; // this is used in Contacts' Emails SubPanel if (!empty($header->toaddress)) { $email->to_name = $this->handleMimeHeaderDecode($header->toaddress); $email->to_addrs_names = $email->to_name; } if (!empty($header->to)) { $email->to_addrs = $this->convertImapToSugarEmailAddress($header->to); } $email->from_name = $this->handleMimeHeaderDecode($header->fromaddress); $email->from_addr_name = $email->from_name; $email->from_addr = $this->convertImapToSugarEmailAddress($header->from); if (!empty($header->cc)) { $email->cc_addrs = $this->convertImapToSugarEmailAddress($header->cc); } if (!empty($header->ccaddress)) { $email->cc_addrs_names = $this->handleMimeHeaderDecode($header->ccaddress); } // if $email->reply_to_name = $this->handleMimeHeaderDecode($header->reply_toaddress); $email->reply_to_email = $this->convertImapToSugarEmailAddress($header->reply_to); if (!empty($email->reply_to_email)) { $email->reply_to_addr = $email->reply_to_name; } $email->intent = $this->mailbox_type; $email->message_id = $this->compoundMessageId; // filled by importDupeCheck(); $oldPrefix = $this->imagePrefix; if (!$forDisplay) { // Store CIDs in imported messages, convert on display $this->imagePrefix = "cid:"; } // handle multi-part email bodies $email->description_html = $this->getMessageText($msgNo, 'HTML', $structure, $fullHeader, $clean_email); // runs through handleTranserEncoding() already $email->description = $this->getMessageText($msgNo, 'PLAIN', $structure, $fullHeader, $clean_email); // runs through handleTranserEncoding() already $this->imagePrefix = $oldPrefix; // empty() check for body content if (empty($email->description)) { $GLOBALS['log']->debug('InboundEmail Message (id:' . $email->message_id . ') has no body'); } // assign_to group if (!empty($_REQUEST['user_id'])) { $email->assigned_user_id = $_REQUEST['user_id']; } else { // Samir Gandhi : Commented out this code as its not needed //$email->assigned_user_id = $this->group_id; } //Assign Parent Values if set if (!empty($_REQUEST['parent_id']) && !empty($_REQUEST['parent_type'])) { $email->parent_id = $_REQUEST['parent_id']; $email->parent_type = $_REQUEST['parent_type']; $mod = strtolower($email->parent_type); $rel = array_key_exists($mod, $email->field_defs) ? $mod : $mod . "_activities_emails"; //Custom modules rel name if (!$email->load_relationship($rel)) { return FALSE; } $email->{$rel}->add($email->parent_id); } // override $forDisplay w/user pref if ($forDisplay) { if ($this->isAutoImport()) { $forDisplay = false; // triggers save of imported email } } if (!$forDisplay) { $email->save(); $email->new_with_id = false; // to allow future saves by UPDATE, instead of INSERT //// ASSIGN APPROPRIATE ATTRIBUTES TO NEW EMAIL OBJECT /////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////// //// LINK APPROPRIATE BEANS TO NEWLY SAVED EMAIL //$contactAddr = $this->handleLinking($email); //// END LINK APPROPRIATE BEANS TO NEWLY SAVED EMAIL /////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////// //// MAILBOX TYPE HANDLING $this->handleMailboxType($email, $header); //// END MAILBOX TYPE HANDLING /////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////// //// SEND AUTORESPONSE if (!empty($email->reply_to_email)) { $contactAddr = $email->reply_to_email; } else { $contactAddr = $email->from_addr; } if (!$this->isMailBoxTypeCreateCase()) { $this->handleAutoresponse($email, $contactAddr); } //// END SEND AUTORESPONSE /////////////////////////////////////////////////////////////////// //// END IMPORT ONE EMAIL /////////////////////////////////////////////////////////////////// } } else { // only log if not POP3; pop3 iterates through ALL mail if ($this->protocol != 'pop3') { $GLOBALS['log']->info("InboundEmail found a duplicate email: " . $header->message_id); //echo "This email has already been imported"; } return false; } //// END DUPLICATE CHECK /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// //// DEAL WITH THE MAILBOX if (!$forDisplay) { imap_setflag_full($this->conn, $msgNo, '\\SEEN'); // if delete_seen, mark msg as deleted if ($this->delete_seen == 1 && !$forDisplay) { $GLOBALS['log']->info("INBOUNDEMAIL: delete_seen == 1 - deleting email"); imap_setflag_full($this->conn, $msgNo, '\\DELETED'); } } else { // for display - don't touch server files? //imap_setflag_full($this->conn, $msgNo, '\\UNSEEN'); } $GLOBALS['log']->debug('********************************* InboundEmail finished import of 1 email: ' . $email->name); //// END DEAL WITH THE MAILBOX /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// //// TO SUPPORT EMAIL 2.0 $this->email = $email; if (empty($this->email->et)) { $this->email->email2init(); } return true; }