/** * 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_search($this->imap_stream, $search_criteria); $no_of_msgs = $msgs ? count($msgs) : 0; $messages = array(); for ($i = 0; $i < $no_of_msgs; $i++) { // Get Message Unique ID in case mail box changes // in the middle of this operation $message_id = imap_uid($this->imap_stream, $msgs[$i]); $header = imap_header($this->imap_stream, $message_id); $date = date($date_format, $header->udate); $from = $header->from; $fromname = ""; $fromaddress = ""; $subject = ""; 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); } $structure = imap_fetchstructure($this->imap_stream, $message_id); $body = ''; 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, $message_id, $j + 1); } } } else { $body = imap_body($this->imap_stream, $message_id); } // Convert quoted-printable strings (RFC2045) $body = imap_qprint($body); array_push($messages, array('msg_no' => $message_id, 'date' => $date, 'from' => $fromname, 'email' => $fromaddress, 'subject' => $subject, 'body' => $body)); // Mark Message As Read imap_setflag_full($this->imap_stream, $message_id, "\\Seen"); } return $messages; }
/** * Constructor which gets the Mail details from the server * @param String $mBox - Mail Box Connection string * @param Integer $msgno - Mail Message Number * @param Boolean $fetchbody - Used to save the mail information to DB */ function __construct($mBox = false, $msgno = false, $fetchbody = false) { if ($mBox && $msgno) { $this->mBox = $mBox; $this->mMsgNo = $msgno; $loaded = false; // Unique ID based on sequence number $this->mUid = imap_uid($mBox, $msgno); if ($fetchbody) { // Lookup if there was previous cached message $loaded = $this->readFromDB($this->mUid); } if (!$loaded) { parent::__construct($mBox, $msgno, $fetchbody); if ($fetchbody) { // Save for further use $loaded = $this->saveToDB($this->mUid); } } if ($loaded) { $this->setRead(true); $this->setMsgNo(intval($msgno)); } } }
public function get_part($imap, $uid, $mimetype, $structure = false, $partNumber = false) { if (!$structure) { $uid = imap_uid($imap, $uid); //echo "uid->".$uid."<br>"; //echo "ft_uid=>".FT_UID; // die; //error_reporting(0); $structure = imap_fetchstructure($imap, $uid, FT_UID); } //echo "<br/>structure-><pre>".print_r($structure)."</pre>"; if ($structure) { if ($mimetype == $this->get_mime_type($structure)) { if (!$partNumber) { $partNumber = 1; } $text = imap_fetchbody($imap, $uid, $partNumber, FT_UID); switch ($structure->encoding) { case 3: return imap_base64($text); case 4: return imap_qprint($text); default: return $text; } } // multipart if ($structure->type == 1) { foreach ($structure->parts as $index => $subStruct) { $prefix = ""; if ($partNumber) { $prefix = $partNumber . "."; } $data = $this->get_part($imap, $uid, $mimetype, $subStruct, $prefix . ($index + 1)); if ($data) { return $data; } } } } return false; }
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; }
public function temp() { set_time_limit(4000); // Connect to gmail $imapPath = '{imap.gmail.com:993/imap/ssl}INBOX'; $username = '******'; $password = '******'; $imap = imap_open($imapPath, $username, $password) or die('Cannot connect to Gmail: ' . imap_last_error()); $numMessages = imap_num_msg($imap); for ($i = $numMessages; $i > $numMessages - 1; $i--) { $header = imap_header($imap, $i); $fromInfo = $header->from[0]; $replyInfo = $header->reply_to[0]; $details = array("fromAddr" => isset($fromInfo->mailbox) && isset($fromInfo->host) ? $fromInfo->mailbox . "@" . $fromInfo->host : "", "fromName" => isset($fromInfo->personal) ? $fromInfo->personal : "", "replyAddr" => isset($replyInfo->mailbox) && isset($replyInfo->host) ? $replyInfo->mailbox . "@" . $replyInfo->host : "", "subject" => isset($header->subject) ? $header->subject : "", "udate" => isset($header->udate) ? $header->udate : ""); $uid = imap_uid($imap, $i); } $body = get_part($imap, $uid, "TEXT/HTML"); // if HTML body is empty, try getting text body /* if ($body == "") { $body = get_part($imap, $uid, "TEXT/PLAIN"); } return $body;*/ // return view('messages.che')->with('body',$body); }
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; }
/** * 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; }
/** * Job 1 */ function pollMonitoredInboxes() { $_bck_up = array('team_id' => $GLOBALS['current_user']->team_id, 'team_set_id' => $GLOBALS['current_user']->team_set_id); Log::info('----->Scheduler fired job of type pollMonitoredInboxes()'); global $dictionary; global $app_strings; require_once 'modules/Emails/EmailUI.php'; $ie = new InboundEmail(); $emailUI = new EmailUI(); $r = $ie->db->query('SELECT id, name FROM inbound_email WHERE is_personal = 0 AND deleted=0 AND status=\'Active\' AND mailbox_type != \'bounce\''); Log::debug('Just got Result from get all Inbounds of Inbound Emails'); while ($a = $ie->db->fetchByAssoc($r)) { Log::debug('In while loop of Inbound Emails'); $ieX = new InboundEmail(); $ieX->retrieve($a['id']); $GLOBALS['current_user']->team_id = $ieX->team_id; $GLOBALS['current_user']->team_set_id = $ieX->team_set_id; $mailboxes = $ieX->mailboxarray; foreach ($mailboxes as $mbox) { $ieX->mailbox = $mbox; $newMsgs = array(); $msgNoToUIDL = array(); $connectToMailServer = false; if ($ieX->isPop3Protocol()) { $msgNoToUIDL = $ieX->getPop3NewMessagesToDownloadForCron(); // get all the keys which are msgnos; $newMsgs = array_keys($msgNoToUIDL); } if ($ieX->connectMailserver() == 'true') { $connectToMailServer = true; } // if Log::debug('Trying to connect to mailserver for [ ' . $a['name'] . ' ]'); if ($connectToMailServer) { Log::debug('Connected to mailserver'); if (!$ieX->isPop3Protocol()) { $newMsgs = $ieX->getNewMessageIds(); } if (is_array($newMsgs)) { $current = 1; $total = count($newMsgs); require_once "include/SugarFolders/SugarFolders.php"; $sugarFolder = new SugarFolder(); $groupFolderId = $ieX->groupfolder_id; $isGroupFolderExists = false; $users = array(); if ($groupFolderId != null && $groupFolderId != "") { $sugarFolder->retrieve($groupFolderId); $isGroupFolderExists = true; } // if $messagesToDelete = array(); if ($ieX->isMailBoxTypeCreateCase()) { $users[] = $sugarFolder->assign_to_id; $distributionMethod = $ieX->get_stored_options("distrib_method", ""); if ($distributionMethod != 'roundRobin') { $counts = $emailUI->getAssignedEmailsCountForUsers($users); } else { $lastRobin = $emailUI->getLastRobin($ieX); } Log::debug('distribution method id [ ' . $distributionMethod . ' ]'); } foreach ($newMsgs as $k => $msgNo) { $uid = $msgNo; if ($ieX->isPop3Protocol()) { $uid = $msgNoToUIDL[$msgNo]; } else { $uid = imap_uid($ieX->conn, $msgNo); } // else if ($isGroupFolderExists) { if ($ieX->importOneEmail($msgNo, $uid)) { // add to folder $sugarFolder->addBean($ieX->email); if ($ieX->isPop3Protocol()) { $messagesToDelete[] = $msgNo; } else { $messagesToDelete[] = $uid; } if ($ieX->isMailBoxTypeCreateCase()) { $userId = ""; if ($distributionMethod == 'roundRobin') { if (sizeof($users) == 1) { $userId = $users[0]; $lastRobin = $users[0]; } else { $userIdsKeys = array_flip($users); // now keys are values $thisRobinKey = $userIdsKeys[$lastRobin] + 1; if (!empty($users[$thisRobinKey])) { $userId = $users[$thisRobinKey]; $lastRobin = $users[$thisRobinKey]; } else { $userId = $users[0]; $lastRobin = $users[0]; } } // else } else { if (sizeof($users) == 1) { foreach ($users as $k => $value) { $userId = $value; } // foreach } else { asort($counts); // lowest to highest $countsKeys = array_flip($counts); // keys now the 'count of items' $leastBusy = array_shift($countsKeys); // user id of lowest item count $userId = $leastBusy; $counts[$leastBusy] = $counts[$leastBusy] + 1; } } // else Log::debug('userId [ ' . $userId . ' ]'); $ieX->handleCreateCase($ieX->email, $userId); } // if } // if } else { if ($ieX->isAutoImport()) { $ieX->importOneEmail($msgNo, $uid); } else { /*If the group folder doesn't exist then download only those messages which has caseid in message*/ $ieX->getMessagesInEmailCache($msgNo, $uid); $email = new Email(); $header = imap_headerinfo($ieX->conn, $msgNo); $email->name = $ieX->handleMimeHeaderDecode($header->subject); $email->from_addr = $ieX->convertImapToSugarEmailAddress($header->from); $email->reply_to_email = $ieX->convertImapToSugarEmailAddress($header->reply_to); if (!empty($email->reply_to_email)) { $contactAddr = $email->reply_to_email; } else { $contactAddr = $email->from_addr; } $mailBoxType = $ieX->mailbox_type; $ieX->handleAutoresponse($email, $contactAddr); } // else } // else Log::debug('***** On message [ ' . $current . ' of ' . $total . ' ] *****'); $current++; } // foreach // update Inbound Account with last robin if ($ieX->isMailBoxTypeCreateCase() && $distributionMethod == 'roundRobin') { $emailUI->setLastRobin($ieX, $lastRobin); } // if } // if if ($isGroupFolderExists) { $leaveMessagesOnMailServer = $ieX->get_stored_options("leaveMessagesOnMailServer", 0); if (!$leaveMessagesOnMailServer) { if ($ieX->isPop3Protocol()) { $ieX->deleteMessageOnMailServerForPop3(implode(",", $messagesToDelete)); } else { $ieX->deleteMessageOnMailServer(implode($app_strings['LBL_EMAIL_DELIMITER'], $messagesToDelete)); } } } } else { Log::fatal("SCHEDULERS: could not get an IMAP connection resource for ID [ {$a['id']} ]. Skipping mailbox [ {$a['name']} ]."); // cn: bug 9171 - continue while } // else } // foreach imap_expunge($ieX->conn); imap_close($ieX->conn, CL_EXPUNGE); } // while $GLOBALS['current_user']->team_id = $_bck_up['team_id']; $GLOBALS['current_user']->team_set_id = $_bck_up['team_set_id']; return true; }
<?php // read mails from internal bounce mailbox and set invalidEmail=1 for these email addresses require '/var/www/yoursite/http/variables.php'; require '/var/www/yoursite/http/variablesdb.php'; require_once '/var/www/yoursite/http/functions.php'; require '/var/www/yoursite/http/log/KLogger.php'; $log = new KLogger('/var/www/yoursite/http/log/bounces/', KLogger::INFO); $mailbox = imap_open('{localhost:993/ssl/novalidate-cert}', 'bounce', 'bounce01$'); $mailbox_info = imap_check($mailbox); for ($i = 1; $i <= $mailbox_info->Nmsgs; $i++) { $msg = imap_fetch_overview($mailbox, $i); $rcpt = $msg[0]->to; if (substr($rcpt, 0, 6) == 'bounce') { $target = substr($rcpt, 7); // exclude 'bounce=' $target = substr($target, 0, -9); // exclude '@yoursite' $target = str_replace('=', '@', $target); // revert '=' to '@' if ($msg[0]->answered == 0) { $sql = "UPDATE {$playerstable} SET invalidEmail=1 WHERE invalidEmail=0 AND mail='" . $target . "'"; mysql_query($sql); $affected = mysql_affected_rows(); $uid = imap_uid($mailbox, $i); $status = imap_setflag_full($mailbox, $uid, '\\Answered \\Seen', ST_UID); $log->logInfo('sql=[' . $sql . '] affected=[' . $affected . '] status=[' . $status . ']'); } } } imap_close($mailbox); // close the mailbox
function pollMonitoredInboxesForBouncedCampaignEmails() { $GLOBALS['log']->info('----->Scheduler job of type pollMonitoredInboxesForBouncedCampaignEmails()'); global $dictionary; $ie = new InboundEmail(); $r = $ie->db->query('SELECT id FROM inbound_email WHERE deleted=0 AND status=\'Active\' AND mailbox_type=\'bounce\''); while ($a = $ie->db->fetchByAssoc($r)) { $ieX = new InboundEmail(); $ieX->retrieve($a['id']); $ieX->connectMailserver(); $GLOBALS['log']->info("Bounced campaign scheduler connected to mail server id: {$a['id']} "); $newMsgs = array(); if ($ieX->isPop3Protocol()) { $newMsgs = $ieX->getPop3NewMessagesToDownload(); } else { $newMsgs = $ieX->getNewMessageIds(); } //$newMsgs = $ieX->getNewMessageIds(); if (is_array($newMsgs)) { foreach ($newMsgs as $k => $msgNo) { $uid = $msgNo; if ($ieX->isPop3Protocol()) { $uid = $ieX->getUIDLForMessage($msgNo); } else { $uid = imap_uid($ieX->conn, $msgNo); } // else $GLOBALS['log']->info("Bounced campaign scheduler will import message no: {$msgNo}"); $ieX->importOneEmail($msgNo, $uid, false, false); } } imap_expunge($ieX->conn); imap_close($ieX->conn); } return true; }
public static function mail_Scan($mbox, $account, $folder, $scan_id) { $return = []; $last_user_uid = self::getUidFolder($account['user_id'], $folder); $msgno = imap_msgno($mbox, $last_user_uid); $num_msg = imap_num_msg($mbox); $get_emails = false; if ($msgno == 0 && $num_msg != 0) { $last_email_uid = imap_uid($mbox, $num_msg); if ($last_user_uid == 1) { $get_emails = true; $msgno = 1; } elseif ($last_email_uid > $last_user_uid) { $exit = true; while ($exit) { $last_user_uid++; $last_scaned_num = imap_msgno($mbox, $last_user_uid); if ($last_scaned_num != 0) { $exit = false; $msgno = $last_scaned_num; } elseif ($last_user_uid == $last_email_uid) { $exit = false; $msgno = $num_msg; } } $get_emails = true; } } else { if ($msgno < $num_msg) { $get_emails = true; } } if ($get_emails) { $return['count'] = 0; for ($i = $msgno; $i <= $num_msg; $i++) { $OSSMailModel = Vtiger_Record_Model::getCleanInstance('OSSMail'); self::checkFolderUid($account['user_id'], $folder); $uid = imap_uid($mbox, $i); $mail_detail = $OSSMailModel->get_mail_detail($mbox, $uid, $i); $mail_detail['Account_username'] = $account['username']; $mail_detail['Account_user_id'] = $account['user_id']; self::executeActions($account, $mail_detail, $folder); $adb = PearDatabase::getInstance(); $adb->pquery("update vtiger_ossmailscanner_folders_uid set uid=? where user_id=? AND folder = ?", array($uid, $account['user_id'], $folder)); self::update_scan_history($scan_id, array('status' => '1', 'count' => $return['count'], 'action' => 'Action_CronMailScanner')); $return['count']++; } } return $return; }
public function appendMessage($message, $box = 'IMAP.Sent', $flags = null, $messageId = null) { $mailbox = $this->imap->reopen($box); $date = null; if ($messageId) { //var_dump($messageId); $messageId = imap_uid($this->connection, $messageId); //var_dump($messageId); $headerinfo = imap_headerinfo($this->connection, $messageId); $date = date('d-M-Y H:i:s O', $headerinfo->udate); } $result = imap_append($this->connection, $mailbox, $message, $flags); $this->fullName = $this->imap->reopen($this->name); return $result; }
/** * Get a sequenced message id * * @param string $msgNo in the format <.*@.*> from the email * * @return mixed on imap its the unique id (int) and for others its a base64_encoded string */ protected function getMessageUId($msgNo) { if ($this->imapStream == null) { return false; } return imap_uid($this->imapStream, $msgNo); }
/** * Read the header of the message * * @param string $msgCount//(邮件ID) * @return array */ public function getHeader($msgCount) { $mailHeader = array(); $header = imap_headerinfo($this->_connect, $msgCount); $sender = $header->from[0]; $replyTo = $header->reply_to[0]; $reciever = $header->to[0]; if (strtolower($sender->mailbox) != 'mailer-daemon' && strtolower($sender->mailbox) != 'postmaster') { $subject = $this->subjectDecode($header->subject); $mailHeader = array('from' => strtolower($sender->mailbox) . '@' . $sender->host, 'fromName' => $this->subjectDecode($sender->personal), 'toOther' => strtolower($replyTo->mailbox) . '@' . $replyTo->host, 'toOtherName' => $replyTo->personal, 'subject' => $subject, 'to' => strtolower($reciever->mailbox) . '@' . $reciever->host, 'toName' => $this->subjectDecode($reciever->personal), 'date' => $header->date, 'id' => $header->Msgno, 'seen' => $header->Unseen, 'msg_id' => imap_uid($this->_connect, $header->Msgno), 'answered' => $header->Answered, 'flagged' => $header->Flagged); } return $mailHeader; }
/** * fetch message by id * * @return header * @param $id of the message */ private function getMessageHeader($id) { $count = $this->countMessages(); for ($i = 1; $i <= $count; $i++) { $uid = imap_uid($this->imap, $i); if ($uid == $id) { $header = imap_headerinfo($this->imap, $i); return $header; } } return false; }
/** * Retrieves message UID by it's number * * @param int $msgNumber Number of the message in current sequence * @param string $protocol Mailing protocol * @return string */ protected function getMessageUID($msgNumber, $protocol) { switch ($protocol) { case 'pop3': $uid = $this->getUIDLForMessage($msgNumber); break; case 'imap': $uid = imap_uid($this->conn, $msgNumber); break; default: $uid = null; break; } return $uid; }
echo $connection->Nmsgs . " message(s) in the inbox, " . $counter . " unread and to process\n\n"; // Process each email foreach ($messages as $message) { // Only process emails that are not marked as seen if (!$message->seen) { // Get the metadata $author = $message->from; $author = trim(preg_replace('/\\<.*\\>/', '', $author)); echo " - Author: {$author}\n"; $title = trim($message->subject); echo " - Title: {$title}\n"; $abstract = trim(strip_tags(imap_fetchbody($inbox, $message->msgno, 1))); echo " - Message: {$abstract}\n"; $info = imap_fetchstructure($inbox, $message->msgno); // Create the package $uid = imap_uid($inbox, $message->msgno); $packagefilename = 'packages/packager-' . $uid . '.zip'; @mkdir('tmp/attachments/' . $uid); $package = new PackagerMetsSwap('tmp', 'attachments/' . $uid, 'tmp', $packagefilename); $package->addCreator($author); $package->setTitle($title); $package->setAbstract($abstract); // Get the attachments / files $type = array("TEXT", "MULTIPART", "MESSAGE", "APPLICATION", "AUDIO", "IMAGE", "VIDEO", "OTHER"); $counter = 1; while (count($info->parts) > 1 && count($info->parts) > $counter) { if ($info->parts[$counter]->ifparameters == 1) { $filename = $info->parts[$counter]->parameters[0]->value; } else { if ($info->parts[$counter]->ifdparameters == 1) { $filename = $info->parts[$counter]->dparameters[0]->value;
*/ echo "*** Testing imap_fetchbody() : basic functionality ***\n"; require_once dirname(__FILE__) . '/imap_include.inc'; // Initialise all required variables // set up mailbox with one message $stream_id = setup_test_mailbox('', 1, $mailbox, 'notSimple'); $msg_no = 1; $section = '2'; $options = array('FT_UID' => FT_UID, 'FT_PEEK' => FT_PEEK, 'FT_INTERNAL' => FT_INTERNAL); // Calling imap_fetchbody() with all possible arguments echo "\n-- All possible arguments --\n"; foreach ($options as $key => $option) { echo "-- Option is {$key} --\n"; switch ($key) { case 'FT_UID': $msg_uid = imap_uid($stream_id, $msg_no); var_dump(imap_fetchbody($stream_id, $msg_uid, $section, $option)); break; case 'FT_PEEK': var_dump(imap_fetchbody($stream_id, $msg_no, $section, $option)); $overview = imap_fetch_overview($stream_id, 1); echo "Seen Flag: "; var_dump($overview[0]->seen); break; case 'FT_INTERNAL': var_dump(imap_fetchbody($stream_id, $msg_no, $section, $option)); break; } } // Calling imap_fetchbody() with mandatory arguments echo "\n-- Mandatory arguments --\n";
/** * liefert die unique ID der Nachricht mit der laufenden msg_number * @param integer $msg_number * @return integer */ public function imapUID($msg_number) { if ($this->imap === null) { throw new IMAPException(__METHOD__ . ' not connected'); } $this->imapPing(true); return imap_uid($this->imap, $msg_number); }
/** * get a usable uuid for use in the code * * @param string $uuid in the format <.*@.*> from the email * * @return mixed on imap its the unique id (int) and for others its a base64_encoded string */ private function __getId($uuid) { switch ($this->__connectionType) { case 'imap': return imap_uid($this->MailServer, $uuid); break; default: return str_replace(array('<', '>'), '', base64_encode($mail->message_id)); break; } }
/** * All email headers */ function email_headers(){ #$headers=imap_headers($this->link); if($this->max_headers == 'max'){ $headers = imap_fetch_overview($this->link, "1:".$this->num_message(), 0); } else { $headers = imap_fetch_overview($this->link, "1:$this->max_headers", 0); } if($this->max_headers == 'max') { $num_headers = count($headers); } else { $count = count($headers); if($this->max_headers >= $count){ $num_headers = $count; } else { $num_headers = $this->max_headers; } } $size=sizeof($headers); for($i=1; $i<=$size; $i++){ $val=$headers[$i]; //while (list($key, $val) = each($headers)){ $subject_s = (empty($val->subject)) ? '[No subject]' : $val->subject; $lp = $lp +1; imap_setflag_full($this->link,imap_uid($this->link,$i),'\\SEEN',SE_UID); $header=imap_headerinfo($this->link, $i, 80,80); if($val->seen == "0" && $val->recent == "0") {echo '<b>'.$val->msgno . '-' . $subject_s . '-' . $val->from .'-'. $val->date."</b><br><hr>" ;} else {echo $val->msgno . '-' . $subject_s . '-' . $val->from .'-'. $val->date."<br><hr>" ;} } }
/** * Retrieve individual messages from an IMAP result. * * @param $result * IMAP stream. * @param object $mailbox * Mailbox to retrieve from. * @param int $msg_number * IMAP message number. * @param string $filter_name * Mailhandler Filter plugin to use. * @return array * Retrieved message, or FALSE if message cannot / should not be retrieved. */ function retrieve_message($result, $mailbox, $msg_number, $filter_name) { extract($mailbox->settings); $header = imap_headerinfo($result, $msg_number); // Check to see if we should retrieve this message at all if ($filter = mailhandler_plugin_load_class('mailhandler', $filter_name, 'filters', 'handler')) { if (!$filter->fetch($header)) { return FALSE; } } // Initialize the subject in case it's missing. if (!isset($header->subject)) { $header->subject = ''; } $body_text = $this->get_part($result, $msg_number, 'text/plain', FALSE, FALSE, $encoding); $body_html = $this->get_part($result, $msg_number, 'text/html', FALSE, FALSE, $encoding); if (!$body_text && $body_html) { $body_text = $body_html; } elseif ($body_text && !$body_html) { $body_html = $body_text; } // Parse MIME parts, so all mailhandler modules have access to // the full array of mime parts without having to process the email. $mimeparts = $this->get_parts($result, $msg_number); // Is this an empty message with no body and no mimeparts? if (!$body_text && !$body_html && !$mimeparts) { $message = FALSE; } else { $imap_uid = $type == 'pop3' ? $this->fetch_uid($mailbox, $msg_number) : imap_uid($result, $msg_number); $message = compact('header', 'body_text', 'body_html', 'mimeparts', 'imap_uid'); } return $message; }
function fetchEmails() { if (!$this->connect()) { return false; } $archiveFolder = $this->getArchiveFolder(); $delete = $this->canDeleteEmails(); $max = $this->getMaxFetch(); $nummsgs = imap_num_msg($this->mbox); //echo "New Emails: $nummsgs\n"; $msgs = $errors = 0; for ($i = $nummsgs; $i > 0; $i--) { //process messages in reverse. if ($this->createTicket($i)) { imap_setflag_full($this->mbox, imap_uid($this->mbox, $i), "\\Seen", ST_UID); //IMAP only?? if ((!$archiveFolder || !imap_mail_move($this->mbox, $i, $archiveFolder)) && $delete) { imap_delete($this->mbox, $i); } $msgs++; $errors = 0; //We are only interested in consecutive errors. } else { $errors++; } if ($max && ($msgs >= $max || $errors > $max * 0.8)) { break; } } //Warn on excessive errors if ($errors > $msgs) { $warn = sprintf(_S('Excessive errors processing emails for %1$s/%2$s. Please manually check the inbox.'), $this->getHost(), $this->getUsername()); $this->log($warn); } @imap_expunge($this->mbox); return $msgs; }
/** * Returns the emails in the current mailbox as an array of Imap_Message objects. * * @param NULL|int $limit * @return array */ public function get_messages($limit = NULL) { $num_messages = $this->num_messages(); if (isset($limit) and is_numeric($limit) and $limit < $num_messages) { $num_messages = $limit; } if ($num_messages < 1) { return FALSE; } $stream = $this->get_imap_stream(); $messages = array(); for ($i = 1; $i <= $num_messages; $i++) { $uid = imap_uid($stream, $i); $messages[] = new Imap_Message($uid, $this); } return $messages; }
while ($a = $ie->db->fetchByAssoc($r)) { $ieX = new InboundEmail(); $ieX->retrieve($a['id']); $ieX->connectMailserver(); //$newMsgs = $ieX->getNewMessageIds(); $newMsgs = array(); if ($ieX->isPop3Protocol()) { $newMsgs = $ieX->getPop3NewMessagesToDownload(); } else { $newMsgs = $ieX->getNewMessageIds(); } if (is_array($newMsgs)) { foreach ($newMsgs as $k => $msgNo) { $uid = $msgNo; if ($ieX->isPop3Protocol()) { $uid = $ieX->getUIDLForMessage($msgNo); } else { $uid = imap_uid($ieX->conn, $msgNo); } // else $ieX->importOneEmail($msgNo, $uid); } } imap_expunge($ieX->conn); imap_close($ieX->conn); } header('Location: index.php?module=Emails&action=ListViewGroup'); } else { // fail gracefully header('Location: index.php?module=Emails&action=index'); }
function getMessageUid($msgno) { return imap_uid($this->stream, $msgno); }
$total_added = 0; $total_time = 0; //go through each mailbox if (is_array($mailboxes)) { foreach ($mailboxes as $key => $val) { $thisBox = imap_utf7_decode($val->name); $boxName = substr($thisBox, strlen($mailboxRoot)); if ($boxName == "Inbox") { $startTime = time(); $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++;
/** * Returns the emails in the current mailbox as an array of ImapMessage objects. * * @param null|int $limit * @return Message[] */ public function getMessages($limit = null) { $numMessages = $this->numMessages(); if (isset($limit) && is_numeric($limit) && $limit < $numMessages) { $numMessages = $limit; } if ($numMessages < 1) { return array(); } $stream = $this->getImapStream(); $messages = array(); for ($i = 1; $i <= $numMessages; $i++) { $uid = imap_uid($stream, $i); $messages[] = new Message($uid, $this); } return $messages; }
/** * Shows one email. * @param int uid UID of email to display * @param string mbox Mailbox to look in for the message * @param bool isMsgNo Flag to assume $uid is a MessageNo, not UniqueID, default false */ function displayOneEmail($uid, $mbox, $isMsgNo = false) { require_once "include/JSON.php"; global $timedate; global $app_strings; global $app_list_strings; global $sugar_smarty; global $theme; global $current_user; global $sugar_config; $fetchedAttributes = array('name', 'from_name', 'from_addr', 'date_start', 'time_start', 'message_id'); $souEmail = array(); foreach ($fetchedAttributes as $k) { if ($k == 'date_start') { $this->email->{$k} . " " . $this->email->time_start; $souEmail[$k] = $this->email->{$k} . " " . $this->email->time_start; } elseif ($k == 'time_start') { $souEmail[$k] = ""; } else { $souEmail[$k] = trim($this->email->{$k}); } } // if a MsgNo is passed in, convert to UID if ($isMsgNo) { $uid = imap_uid($this->conn, $uid); } // meta object to allow quick retrieval for replies $meta = array(); $meta['type'] = $this->email->type; $meta['uid'] = $uid; $meta['ieId'] = $this->id; $meta['email'] = $souEmail; $meta['mbox'] = $this->mailbox; $ccs = ''; // imap vs pop3 // self mapping $exMbox = explode("::", $mbox); // CC section $cc = ''; if (!empty($this->email->cc_addrs)) { //$ccs = $this->collapseLongMailingList($this->email->cc_addrs); $ccs = to_html($this->email->cc_addrs_names); $cc = <<<eoq \t\t\t\t<tr> \t\t\t\t\t<td NOWRAP valign="top" class="displayEmailLabel"> \t\t\t\t\t\t{$app_strings['LBL_EMAIL_CC']}: \t\t\t\t\t</td> \t\t\t\t\t<td class="displayEmailValue"> \t\t\t\t\t\t{$ccs} \t\t\t\t\t</td> \t\t\t\t</tr> eoq; } $meta['cc'] = $cc; $meta['email']['cc_addrs'] = $ccs; // attachments $attachments = ''; if ($mbox == "sugar::Emails") { $q = "SELECT id, filename, file_mime_type FROM notes WHERE parent_id = '{$uid}' AND deleted = 0"; $r = $this->db->query($q); $i = 0; while ($a = $this->db->fetchByAssoc($r)) { $url = "index.php?entryPoint=download&type=notes&id={$a['id']}"; $lbl = $i == 0 ? $app_strings['LBL_EMAIL_ATTACHMENTS'] . ":" : ''; $i++; $attachments .= <<<EOQ \t\t\t\t<tr> \t\t\t\t\t\t\t<td NOWRAP valign="top" class="displayEmailLabel"> \t\t\t\t\t\t\t\t{$lbl} \t\t\t\t\t\t\t</td> \t\t\t\t\t\t\t<td NOWRAP valign="top" colspan="2" class="displayEmailValue"> \t\t\t\t\t\t\t\t<a href="{$url}">{$a['filename']}</a> \t\t\t\t\t\t\t</td> \t\t\t\t\t\t</tr> EOQ; $this->email->cid2Link($a['id'], $a['file_mime_type']); } // while } else { if ($this->attachmentCount > 0) { $theCount = $this->attachmentCount; for ($i = 0; $i < $theCount; $i++) { $lbl = $i == 0 ? $app_strings['LBL_EMAIL_ATTACHMENTS'] . ":" : ''; $name = $this->getTempFilename(true) . $i; $tempName = urlencode($this->tempAttachment[$name]); $url = "index.php?entryPoint=download&type=temp&isTempFile=true&ieId={$this->id}&tempName={$tempName}&id={$name}"; $attachments .= <<<eoq \t\t\t\t\t\t<tr> \t\t\t\t\t\t\t<td NOWRAP valign="top" class="displayEmailLabel"> \t\t\t\t\t\t\t\t{$lbl} \t\t\t\t\t\t\t</td> \t\t\t\t\t\t\t<td NOWRAP valign="top" colspan="2" class="displayEmailValue"> \t\t\t\t\t\t\t\t<a href="{$url}">{$this->tempAttachment[$name]}</a> \t\t\t\t\t\t\t</td> \t\t\t\t\t\t</tr> eoq; } // for } // if } // else $meta['email']['attachments'] = $attachments; // toasddrs $meta['email']['toaddrs'] = $this->collapseLongMailingList($this->email->to_addrs); $meta['email']['cc_addrs'] = $ccs; // body $description = empty($this->email->description_html) ? nl2br($this->email->description) : $this->email->description_html; $meta['email']['description'] = $description; // meta-metadata $meta['is_sugarEmail'] = $exMbox[0] == 'sugar' ? true : false; if (!$meta['is_sugarEmail']) { if ($this->isAutoImport) { $meta['is_sugarEmail'] = true; } } else { if ($this->email->status != 'sent') { // mark SugarEmail read $q = "UPDATE emails SET status = 'read' WHERE id = '{$uid}'"; $r = $this->db->query($q); } } $return = array(); $meta['email']['name'] = to_html($this->email->name); $meta['email']['from_addr'] = !empty($this->email->from_addr_name) ? to_html($this->email->from_addr_name) : to_html($this->email->from_addr); $meta['email']['toaddrs'] = !empty($this->email->to_addrs_names) ? to_html($this->email->to_addrs_names) : to_html($this->email->to_addrs); $meta['email']['cc_addrs'] = to_html($this->email->cc_addrs_names); $meta['email']['reply_to_addr'] = to_html($this->email->reply_to_addr); $return['meta'] = $meta; return $return; }
public static function mail_Scan($mbox, $account, $folder, $scan_id, $countEmails) { $last_user_uid = self::getUidFolder($account['user_id'], $folder); $msgno = imap_msgno($mbox, $last_user_uid); $num_msg = imap_num_msg($mbox); $get_emails = false; if ($msgno == 0 && $num_msg != 0) { $last_email_uid = imap_uid($mbox, $num_msg); if ($last_user_uid == 1) { $get_emails = true; $msgno = 1; } elseif ($last_email_uid > $last_user_uid) { $exit = true; while ($exit) { $last_user_uid++; $last_scaned_num = imap_msgno($mbox, $last_user_uid); if ($last_scaned_num != 0) { $exit = false; $msgno = $last_scaned_num; } elseif ($last_user_uid == $last_email_uid) { $exit = false; $msgno = $num_msg; } } $get_emails = true; } } else { if ($msgno < $num_msg) { $get_emails = true; } } if ($get_emails) { for ($i = $msgno; $i <= $num_msg; $i++) { $OSSMailModel = Vtiger_Record_Model::getCleanInstance('OSSMail'); self::checkFolderUid($account['user_id'], $folder); $uid = imap_uid($mbox, $i); $mail_detail = $OSSMailModel->get_mail_detail($mbox, $uid, $i); $mail_detail['Account_username'] = $account['username']; $mail_detail['Account_user_id'] = $account['user_id']; self::executeActions($account, $mail_detail, $folder); $adb = PearDatabase::getInstance(); $adb->pquery('UPDATE vtiger_ossmailscanner_folders_uid SET uid=? WHERE user_id=? AND BINARY folder = ?', [$uid, $account['user_id'], $folder]); $countEmails++; self::update_scan_history($scan_id, ['status' => '1', 'count' => $countEmails, 'action' => 'Action_CronMailScanner']); if ($countEmails >= AppConfig::performance('NUMBERS_EMAILS_DOWNLOADED_DURING_ONE_SCANNING')) { return $countEmails; } } } return $countEmails; }