/** * 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; }
public function readEmails($sentTo = null, $bodyPart = null) { $host = '{imap.gmail.com:993/imap/ssl}INBOX'; $spinner = new Spinner('Could not connect to Imap server.', 60, 10000); $inbox = $spinner->assertBecomesTrue(function () use($host) { return @imap_open($host, $this->email, $this->password); }); $emails = imap_search($inbox, 'TO ' . ($sentTo ? $sentTo : $this->email)); if ($emails) { $messages = []; foreach ($emails as $n) { $structure = imap_fetchstructure($inbox, $n); if (!$bodyPart) { $part = $this->findPart($structure, function ($part) { return $part->subtype === 'HTML'; }); } elseif (is_callable($bodyPart)) { $part = $this->findPart($structure, $bodyPart); } else { $part = $bodyPart; } $hinfo = imap_headerinfo($inbox, $n); $subject = $hinfo->subject; $message = ['subject' => $subject, 'body' => imap_fetchbody($inbox, $n, $part)]; $messages[] = $message; } return $messages; } else { return []; } }
/** * @return \Ephp\ImapBundle\Entity\Header */ protected function getHeader($mid, $inbox = null) { if (!$inbox) { $inbox = $this->inbox; } $header = imap_headerinfo($inbox, $mid); if (!$header) { throw new \Exception('Email not found'); } $out = new \Ephp\ImapBundle\Entity\Header(); if (isset($header->Subject)) { $out->setSubject($header->Subject); } elseif (isset($header->subject)) { $out->setSubject($header->subject); } else { $out->setSubject('no subject'); } $out->setSize($header->Size); $out->setDate($header->Date); $out->setMessageId($header->message_id); if (isset($header->to)) { $out->setTo($header->to); } if (isset($header->from)) { $out->setFrom($header->from); } if (isset($header->cc)) { $out->setCc($header->cc); } if (isset($header->bcc)) { $out->setBcc($header->bcc); } return $out; }
function inbox() { $this->msg_cnt = imap_num_msg($this->conn); $in = array(); for ($i = 1; $i <= 20; $i++) { $in[] = array('index' => $i, 'header' => imap_headerinfo($this->conn, $i), 'body' => imap_body($this->conn, $i), 'structure' => imap_fetchstructure($this->conn, $i)); } $this->inbox = $in; }
/** * Get messages according to a search criteria * * @param string search criteria (RFC2060, sec. 6.4.4). Set to "UNSEEN" by default * NB: Search criteria only affects IMAP mailboxes. * @param string date format. Set to "Y-m-d H:i:s" by default * @return mixed array containing messages */ public function get_messages($search_criteria = "UNSEEN", $date_format = "Y-m-d H:i:s") { //$msgs = imap_num_msg($this->imap_stream); $no_of_msgs = imap_num_msg($this->imap_stream); $messages = array(); for ($i = 1; $i <= $no_of_msgs; $i++) { $header = imap_headerinfo($this->imap_stream, $i); $message_id = $header->message_id; $date = date($date_format, $header->udate); if (isset($header->from)) { $from = $header->from; } else { $from = FALSE; } $fromname = ""; $fromaddress = ""; $subject = ""; if ($from != FALSE) { foreach ($from as $id => $object) { if (isset($object->personal)) { $fromname = $object->personal; } $fromaddress = $object->mailbox . "@" . $object->host; if ($fromname == "") { // In case from object doesn't have Name $fromname = $fromaddress; } } } if (isset($header->subject)) { $subject = $this->_mime_decode($header->subject); } // Read the message structure $structure = imap_fetchstructure($this->imap_stream, $i); if (!empty($structure->parts)) { for ($j = 0, $k = count($structure->parts); $j < $k; $j++) { $part = $structure->parts[$j]; if ($part->subtype == 'PLAIN') { $body = imap_fetchbody($this->imap_stream, $i, $j + 1); } } } else { $body = imap_body($this->imap_stream, $i); } // Convert quoted-printable strings (RFC2045) $body = imap_qprint($body); // Convert to valid UTF8 $body = htmlentities($body); $subject = htmlentities($subject); array_push($messages, array('message_id' => $message_id, 'date' => $date, 'from' => $fromname, 'email' => $fromaddress, 'subject' => $subject, 'body' => $body)); // Mark Message As Read imap_setflag_full($this->imap_stream, $i, "\\Seen"); } return $messages; }
public function __construct($Number, &$Mailbox) { $this->Mailbox =& $Mailbox; $Connection =& $this->Mailbox->Connection; $Tmp = imap_fetch_overview($Connection, $Number); $this->Overview = $Tmp[0]; $this->Structure = imap_fetchstructure($Connection, $Number); $this->HeaderInfo = imap_headerinfo($Connection, $Number); $this->MailDateTime = Gdn_Format::ToDateTime($this->HeaderInfo->udate); $this->Number = $this->Overview->msgno; $this->Uid = $this->Overview->uid; $this->RetrieveInfo(); $this->RetrieveBodyText(); $this->RetrieveAttachments(); return $this; }
function readImapStatus($config, $savedStatus, $db) { $mbox = imap_open($config["imap_server"], $config["imap_user"], $config["imap_password"]); $imapStatus = imap_status($mbox, $config["imap_server"], SA_ALL); // Read message IDs of UNSEEN mails $unseen = []; if ($imapStatus->unseen > 0) { $messages = imap_search($mbox, "UNSEEN"); foreach ($messages as $msgID) { $msg = imap_headerinfo($mbox, $msgID); $unseen[] = $msg->message_id; } } imap_close($mbox); // $last_unseen = json_decode($savedStatus->unseen); $new_message_found = false; foreach ($unseen as $key => $value) { // Does 'unseen' contain msgID we haven't seen before? if (array_search($value, $last_unseen) === FALSE) { $new_message_found = true; } } // Current unseen list doesn't match saved one if (count($unseen) != count($last_unseen) || $new_message_found) { saveStatusToSqlite($db, "unseen", json_encode($unseen)); } return $new_message_found; }
/** * Open mail from Imap and parse structure * @license http://www.gnu.org/copyleft/gpl.html GPL * @author Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br) * @return string menssagem */ public function setStructureFromMail($folder, $msgNumber) { $this->folder = mb_convert_encoding($folder, 'UTF7-IMAP', mb_detect_encoding($folder . 'x', 'UTF-8, ISO-8859-1')); $this->msgNumber = $msgNumber; $this->username = $_SESSION['phpgw_info']['expressomail']['user']['userid']; $this->password = $_SESSION['phpgw_info']['expressomail']['user']['passwd']; $this->imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer']; $this->imap_port = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort']; $this->imap_delimiter = $_SESSION['phpgw_info']['expressomail']['email_server']['imapDelimiter']; $this->imap_sentfolder = $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder'] ? $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder'] : str_replace("*", "", $this->functions->getLang("Sent")); $this->has_cid = false; if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes') { $this->imap_options = '/tls/novalidate-cert'; } else { $this->imap_options = '/notls/novalidate-cert'; } $this->mbox = @imap_open("{" . $this->imap_server . ":" . $this->imap_port . $this->imap_options . "}" . $this->folder, $this->username, $this->password) or die('Error'); $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $this->msgNumber), 80, 255); $this->messageId = $header->message_id; $rawMessageData = $this->_getRaw(); $decoder = new Mail_mimeDecode($rawMessageData); $this->structure = $decoder->decode($this->decodeConf); //TODO: Descartar código após atualização do módulo de segurança da SERPRO if ($this->isSignedMenssage()) { $this->convertSignedMenssage($rawMessageData); } ////////////////////////////////////////////////////// /* * Clean memory and close imap connection */ $rawMessageData = null; $decoder = null; @imap_close($this->mbox); //-----------------------------------------// }
function emailListener() { $connection = establishConnection(); $dbConn = establishDBConnection(); $messagestatus = "UNSEEN"; $emails = imap_search($connection, $messagestatus); if ($emails) { rsort($emails); foreach ($emails as $email_number) { // echo "in email loop"; $header = imap_headerinfo($connection, $email_number); $message = imap_fetchbody($connection, $email_number, 1.1); if ($message == "") { $message = imap_fetchbody($connection, $email_number, 1); } $emailaddress = substr($header->senderaddress, stripos($header->senderaddress, "<") + 1, stripos($header->senderaddress, ">") - (stripos($header->senderaddress, ">") + 1)); if (!detectOOOmessage($header->subject, $message, $emailaddress)) { detectBIOmessage($header->subject, $emailaddress); } imap_delete($connection, 1); //this might bug out but should delete the top message that was just parsed } } $dbConn->query("DELETE FROM away_mentor WHERE tiStamp <= DATE_ADD(NOW(), INTERVAL -1 DAY) limit 1"); //delete mentors that have been away for more than 24 hours from the away list }
function imap_get_mail_array() { for ($i = 1; $i < $this->__imap_count_mail() + 1; $i++) { $mailHeader[] = @imap_headerinfo($conn, $i); } return $mailHeader; }
function get_header($msg_number) { if (isset($this->header[$msg_number])) { return $this->header[$msg_number]; } $this->header[$msg_number] = imap_headerinfo($this->imap, $msg_number); return $this->header[$msg_number]; }
function get_plain_text_subject($mbox, $msgNum, $headers = null) { $headers or $headers = imap_headerinfo($mbox, $msgNum); $subjectParts = imap_mime_header_decode($headers->Subject); $subject = ''; foreach ($subjectParts as $p) { $subject .= $p->text; } return trim($subject); }
private function getHeader() { if (!isset($this->header)) { try { $this->header = imap_headerinfo($this->imap_stream, $this->message_index, 800, 800); } catch (Exception $e) { return false; } } return $this->header; }
/** * @param int $limit */ public function inbox($limit = null) { $this->msg_cnt = imap_num_msg($this->conn); if ($limit && $limit < $this->msg_cnt) { $this->msg_cnt = $limit; } $in = array(); for ($i = 1; $i <= $this->msg_cnt; $i++) { $in[] = array('index' => $i, 'header' => @imap_headerinfo($this->conn, $i), 'body' => @imap_body($this->conn, $i), 'structure' => @imap_fetchstructure($this->conn, $i)); } $this->inbox = $in; }
public function getMessage($msg_id = 1) { $message = new MailMessage(); if ($this->getNumMessages() > 0) { $header_info = imap_headerinfo($this->box, $msg_id); $message->setSubject($header_info->subject); $message->setSenderAddress($header_info->from[0]->mailbox . "@" . $header_info->from[0]->host); $message->setMessage(imap_fetchbody($this->box, $msg_id, 1)); $this->addAttachments($message, $msg_id); return $message; } }
/** * @param string $search */ public static function search($search = 'UNSEEN') { $data = imap_search(self::$mbox, $search); $messages = array(); if ($data !== false) { foreach ($data as $i) { $headerArr = imap_headerinfo(self::$mbox, $i); self::getMsg($i); $messages[] = array('from' => $headerArr->sender[0]->mailbox . "@" . $headerArr->sender[0]->host, 'to' => $headerArr->to[0]->mailbox . "@" . $headerArr->to[0]->host, 'date' => $headerArr->date, 'size' => $headerArr->Size, 'charset' => self::$charset, 'name' => self::decode($headerArr->sender[0]->personal), 'subject' => self::decode($headerArr->subject), 'plain' => self::$plainmsg, 'html' => self::$htmlmsg, 'attach' => self::$attachments); imap_setflag_full(self::$mbox, $i, "\\Seen"); } self::$messages = $messages; unset($messages); } }
function get_headers($msg) { $header = imap_headerinfo($this->_connection, $msg); $result['from'] = $header->fromaddress; $result['to'] = $header->toaddress; $result['recipient'] = $header->toaddress; $result['sender'] = $header->senderaddress; $result['reply_to'] = $header->reply_toaddress; $result['size'] = $header->Size; $result['subject'] = $header->subject; $result['date_sent_str'] = $header->MailDate; $result['udate_sent'] = $header->udate; $result['date_sent'] = date('Y-m-d H:i:s', $header->udate); return $result; }
public function readMessage($imap, $email_number) { $message['header'] = imap_headerinfo($imap, $email_number, 0); $message['overview'] = imap_fetch_overview($imap, $email_number, 0); $message['body'] = imap_fetchbody($imap, $email_number, 2); //$output = ''; /* output the email header information * $output.= '<div class="toggler '.($overview[0]->seen ? 'read' : 'unread').'">'; $output.= '<span class="subject">'.$overview[0]->subject.'</span> '; $output.= '<span class="from">'.$overview[0]->from.'</span>'; $output.= '<span class="date">on '.$overview[0]->date.'</span>'; $output.= '</div>'; /* output the email body */ //$output.= '<div class="body">'.$message.'</div>'; return $message; }
function emailListener() { //$output = "<script>console.log( 'just got in' );</script>"; //echo $output; $connection = establishConnection(); $dbConn = establishDBConnection(); //$output = "<script>console.log( 'set up connection' );</script>"; //$dbConn->query("INSERT INTO away_mentor (userID, tiStamp) VALUES (99897, NOW())");//test the db connection //echo $output;//develop thread/loop $messagestatus = "UNSEEN"; $countTo24 = 0; while (true) { echo "in check loop"; $emails = imap_search($connection, $messagestatus); if ($emails) { rsort($emails); foreach ($emails as $email_number) { echo "in email loop"; $header = imap_headerinfo($connection, $email_number); $message = imap_fetchbody($connection, $email_number, 1.1); if ($message == "") { $message = imap_fetchbody($connection, $email_number, 1); } $emailaddress = substr($header->senderaddress, stripos($header->senderaddress, "<") + 1, stripos($header->senderaddress, ">") - (stripos($header->senderaddress, ">") + 1)); if (!detectOOOmessage($header->subject, $message, $emailaddress)) { detectB00message($header->subject, $emailaddress); } imap_delete($connection, 1); //this might bug out but should delete the top message that was just parsed } } sleep(600); //do check every 10 minutes $countTo24 = $countTo24 + 1; if ($countTo24 >= 144) { $countTo24 = 0; $dbConn->query("DELETE FROM away_mentor WHERE tiStamp <= DATE_ADD(CURRENT_DATE, INTERVAL -1 DAY)"); //delete mentors that have been away for more than 24 hours from the away list //$command = Yii::app()->db->createCommand(); // $command->delete('away_mentor', 'tiStamp <= DATE_ADD(CURRENT_DATE , INTERVAL -1 DAY )');//this might bug the hell out deletes mentors on the away list that were put on over 24 hours ago } if (!imap_ping($connection)) { $connection = establishConnection(); } } }
function getHeader($uid) { $aheader = array(); $aheader['uid'] = $uid; $aheader['msgno'] = $this->amsgnobyuid[$uid]; $hi = imap_headerinfo($this->hconnection, $this->amsgnobyuid[$uid], 80, 80); $aheader['ssubject'] = $this->decodeHeaderPart($hi->subject); $aheader['sfrom'] = trim(strtolower($hi->from[0]->mailbox . "@" . $hi->from[0]->host)); $aheader['sfromname'] = $this->decodeHeaderPart($hi->from[0]->personal); $aheader['scccoded'] = $hi->ccaddress; $a = imap_mime_header_decode($hi->ccaddress); $s = ''; for ($i = 0; $i < count($a); $i++) { $s .= $a[$i]->text; } $aheader['sccorg'] = $s; //$aheader['treceived'] = $this->getRecDate($hi->date); $aheader['treceived'] = date('Y-m-d H:i', $hi->udate); // echo "hi-to\n"; // print_r($hi->to); // $aheader['atos'] = $this->arrayizeMaillist($hi->to); $aheader['accs'] = $this->arrayizeMaillist($hi->cc); $aheader['scc'] = implode(',', $aheader['accs']); $header = $this->aheadersbyuid[$uid]; $aheader['stocoded'] = $header->to; $a = imap_mime_header_decode($header->to); $s = ''; for ($i = 0; $i < count($a); $i++) { $s .= $a[$i]->text; } $aheader['stoorg'] = $s; $hrfc = imap_rfc822_parse_headers(imap_fetchheader($this->hconnection, $uid, FT_UID)); // echo "hrfc\n"; // print_r($hrfc); $aheader['atos'] = $this->arrayizeMaillist($hrfc->to); $aheader['sto'] = implode(',', $aheader['atos']); $aheader['tdate'] = $header->date; $aheader['nsize'] = $header->size; $aheader['bseen'] = $header->seen; $aheader['bunread'] = !$header->seen; $aheader['npriority'] = $header->x - priority; return $aheader; }
public function getEmailInfo($messageNumber) { $body = nl2br(strip_tags(imap_body($this->conn, $messageNumber))); $header = imap_header($this->conn, $messageNumber); // For getting From and then display name/email address $from2 = $header->from; // Get display from name and email address: $fromname = $fromaddress = ''; foreach ($from2 as $id => $object) { $fromname = property_exists($object, 'personal') ? $object->personal : ''; $fromaddress = property_exists($object, 'mailbox') ? $object->mailbox . "@" . $object->host : ''; } // End foreach. $mailHeader = imap_headerinfo($this->conn, $messageNumber); // For gleaning subject and date. $subject = strip_tags($mailHeader->subject); $date = $mailHeader->date; return array($body, $fromname, $fromaddress, $subject, $date); }
public function showEmails() { $connect_to = '{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX'; $user = '******'; $password = '******'; $inbox = imap_open($connect_to, $user, $password) or die("Can't connect to '{$connect_to}': " . imap_last_error()); $folders = imap_list($inbox, "{imap.gmail.com:993/imap/ssl}", "*"); //return dd($folders); //return $message_count = imap_num_msg($inbox); $emails = imap_search($inbox, 'SINCE ' . date('d-M-Y', strtotime("-2 week"))); $output = []; $emailCount = imap_num_msg($inbox); rsort($emails); $i = 0; foreach ($emails as $mail) { $headerInfo = imap_headerinfo($inbox, $mail); //return var_dump(dd($headerInfo)); $message = ""; $output[$i]['subject'] = isset($headerInfo->Subject) ? imap_utf8($headerInfo->Subject) : "0"; $output[$i]['from'] = imap_utf8($headerInfo->from[0]->personal); $output[$i]['toaddress'] = $headerInfo->toaddress; $output[$i]['to'] = array_shift($headerInfo->to); $output[$i]['date'] = $headerInfo->date[0]; $output[$i]['fromaddress'] = $headerInfo->fromaddress[0]; $output[$i]['reply_toaddress'] = $headerInfo->reply_toaddress[0]; $output[$i]['date'] = date('d-m-Y ' . '[' . 'H:i' . ']', strtotime($headerInfo->date) + 3600); $output[$i]['unseen'] = $headerInfo->Unseen; $output[$i]['flagged'] = $headerInfo->Flagged; $message = imap_fetchbody($inbox, $mail, 2); if (base64_decode($message, true)) { //message body if base64 encoded $message = base64_decode($message); } else { //message body is not base64 encoded $message = imap_fetchbody($inbox, $mail, 1); } $output[$i]['body'] = $message; $i++; } return dd($output); //return view('aßdministration.email.showEmails')->with('output', $output); }
function get_one_mail($number) { $mail = imap_headerinfo($this->connection, $number); //echo "<hr/>"; //echo "mail nummer: ".$number."<br/>"; //echo "date: ".$mail->date."<br/>"; //echo "subject: ".$mail->subject."<br/>"; //echo "from-mailbox: ".$mail->from[0]->mailbox."<br/>"; //echo "from-host: ".$mail->from[0]->host."<br/>"; $this->mails[$number]["date"]["raw"] = $mail->date; $this->mails[$number]["date"]["timestamp"] = strtotime($mail->date); $last_char_1 = substr($mail->subject, -1, 1); $cleansubject = $mail->subject; $cleansubject = utf8_encode(imap_qprint($cleansubject)); $cleansubject = ereg_replace("=\\?ISO-8859-1\\?Q\\?", "", $cleansubject); $cleansubject = ereg_replace("\\?=", "", $cleansubject); $cleansubject = ereg_replace("_", " ", $cleansubject); $last_char_2 = substr($cleansubject, -1, 1); if ($last_char_1 != $last_char_2) { $cleansubject = substr($cleansubject, 0, strlen($cleansubject) - 1); } //$cleansubject = ereg_replace("?", "", $cleansubject); $this->mails[$number]["subject"] = $cleansubject; $this->mails[$number]["mailbox"] = $mail->from[0]->mailbox; $this->mails[$number]["host"] = $mail->from[0]->host; $body = utf8_encode(imap_qprint(imap_fetchbody($this->connection, $number, "1"))); if ($body != "") { $this->mails[$number]["text"] = $body; } $struct = imap_fetchstructure($this->connection, $number); //print_r($struct); $counter = 2; while (imap_fetchbody($this->connection, $number, $counter) != "") { $image = imap_fetchbody($this->connection, $number, $counter); $this->mails[$number]["image"][$counter]["data"] = $image; $parts = $counter - 1; $this->mails[$number]["image"][$counter]["name"] = $struct->parts[$parts]->dparameters[0]->value; $this->email_base64_to_file($number, $counter); $counter++; } }
public function getMails() { /*echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head><body>';*/ $message_count = imap_num_msg($this->MailBoxHandle); for ($counter = 1; $counter <= $message_count; $counter++) { // echo "<h1>Headers in INBOX</h1>\n"; $headers = imap_headerinfo($this->MailBoxHandle,$counter); $structure = imap_fetchstructure($this->MailBoxHandle,$counter); $ttype = $structure->type; $tcode = $structure->encoding; $body = imap_body($this->MailBoxHandle,$counter,1); if ( $tcode == 3 ) { $body = base64_decode($body); $value= $body; if (isset($structure->parameters[0]->attribute) && $structure->parameters[0]->attribute=='CHARSET'); { if ($structure->parameters[0]->value=='iso-8859-1') { $body = str_replace("\r\n", "<br />",iconv("ISO-8859-1", "UTF-8",$body)); } } } if ( $tcode == 4 ) { $body = quoted_printable_decode($body); $body = str_replace("\r\n", "<br />",iconv("ISO-8859-1", "UTF-8",$body)); } // echo "<br />".$body; } imap_close($this->MailBoxHandle); }
function parseheader($conn, $msgno) { $header = imap_headerinfo($conn, $msgno); $header_a = array(); if (isset($header->to) && !empty($header->to)) { foreach ($header->to as $to) { $header_a['to'][] = $to->mailbox . '@' . $to->host; } } if (isset($header->from) && !empty($header->from)) { foreach ($header->from as $from) { $header_a['from'][] = array('addr' => $from->mailbox . '@' . $from->host, 'person' => isset($from->personal) && $from->personal ? $from->personal : ''); } } if (isset($header->reply_to) && !empty($header->reply_to)) { foreach ($header->reply_to as $reply_to) { $header_a['reply_to'][] = array('addr' => $reply_to->mailbox . '@' . $reply_to->host, 'person' => isset($reply_to->personal) && $reply_to->personal ? $reply_to->personal : ''); } } if (isset($header->cc) && !empty($header->cc)) { foreach ($header->cc as $cc) { $header_a['cc'][] = array('addr' => $cc->mailbox . '@' . $cc->host, 'person' => isset($cc->personal) && $cc->personal ? $cc->personal : ''); } } if (isset($header->subject)) { $header_a['subject'] = imap_utf8($header->subject); } else { $header_a['subject'] = ''; } $header_a['recent'] = $header->Recent; $header_a['unseen'] = $header->Unseen; $header_a['flagged'] = $header->Flagged; $header_a['deleted'] = $header->Deleted; $header_a['draft'] = $header->Draft; $header_a['date'] = $header->udate; $header_a['msgno'] = $msgno; return $header_a; }
/** 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); } } }
function getMailsFromIMAP($user = false) { $account = self::getAccountsList($user, true); $mails = []; $mailLimit = 5; if ($account) { $imap = self::imapConnect($account[0]['username'], $account[0]['password'], $account[0]['mail_host']); $numMessages = imap_num_msg($imap); if ($numMessages < $mailLimit) { $mailLimit = $numMessages; } for ($i = $numMessages; $i > $numMessages - $mailLimit; $i--) { $header = imap_headerinfo($imap, $i); $mail_detail = self::get_mail_detail($imap, false, $i); $mails[] = $mail_detail; } imap_close($imap); } return $mails; }
/** * Gets the mail from the inbox * Reads all the messages there, and adds posts based on them. Then it deletes the entire mailbox. */ function getMail() { $config = Config::current(); if (time() - 60 * $config->emailblog_minutes >= $config->emailblog_mail_checked) { $hostname = '{' . $config->emailblog_server . '}INBOX'; # this isn't working well on localhost $username = $config->emailblog_address; $password = $config->emailblog_pass; $subjpass = $config->emailblog_subjpass; $inbox = imap_open($hostname, $username, $password) or exit("Cannot connect to Gmail: " . imap_last_error()); $emails = imap_search($inbox, 'SUBJECT "' . $subjpass . '"'); if ($emails) { rsort($emails); foreach ($emails as $email_number) { $message = imap_body($inbox, $email_number); $overview = imap_headerinfo($inbox, $email_number); imap_delete($inbox, $email_number); $title = htmlspecialchars($overview->Subject); $title = preg_replace($subjpass, "", $title); $clean = strtolower($title); $body = htmlspecialchars($message); # The subject of the email is used as the post title # the content of the email is used as the body # not sure about compatibility with images or audio feathers Post::add(array("title" => $title, "body" => $message), $clean, Post::check_url($clean), "text"); } } # close the connection imap_close($inbox, CL_EXPUNGE); $config->set("emailblog_mail_checked", time()); } }
/** * 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; }