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 [];
     }
 }
 function getAttachments($id, $path)
 {
     $parts = imap_fetchstructure($this->mailbox, $id);
     $attachments = array();
     //FIXME if we do an is_array() here it breaks howver if we don't
     //we get foreach errors
     foreach ($parts->parts as $key => $value) {
         $encoding = $parts->parts[$key]->encoding;
         if ($parts->parts[$key]->ifdparameters) {
             $filename = $parts->parts[$key]->dparameters[0]->value;
             $message = imap_fetchbody($this->mailbox, $id, $key + 1);
             switch ($encoding) {
                 case 0:
                     $message = imap_8bit($message);
                 case 1:
                     $message = imap_8bit($message);
                 case 2:
                     $message = imap_binary($message);
                 case 3:
                     $message = imap_base64($message);
                 case 4:
                     $message = quoted_printable_decode($message);
                 case 5:
                 default:
                     $message = $message;
             }
             $fp = fopen($path . $filename, "w");
             fwrite($fp, $message);
             fclose($fp);
             $attachments[] = $filename;
         }
     }
     return $attachments;
 }
Example #3
3
 /**
  * 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;
 }
Example #4
2
 /**
 * 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++) {
         $header = imap_header($this->imap_stream, $msgs[$i]);
         $date = date($date_format, $header->udate);
         $from = $this->_mime_decode($header->fromaddress);
         $subject = $this->_mime_decode($header->subject);
         $structure = imap_fetchstructure($this->imap_stream, $msgs[$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, $msgs[$i], $j + 1);
                 }
             }
         } else {
             $body = imap_body($this->imap_stream, $msgs[$i]);
         }
         // Convert quoted-printable strings (RFC2045)
         $body = imap_qprint($body);
         array_push($messages, array('msg_no' => $msgs[$i], 'date' => $date, 'from' => $from, 'subject' => $subject, 'body' => $body));
     }
     return $messages;
 }
Example #5
2
 public function fetch($delete = false)
 {
     $oImap = imap_open('{' . $this->mail_server . ':993/imap/ssl/notls/novalidate-cert}', $this->username, $this->password);
     $oMailboxStatus = imap_check($oImap);
     $aMessages = imap_fetch_overview($oImap, "1:{$oMailboxStatus->Nmsgs}");
     $validMessages = array();
     foreach ($aMessages as $oMessage) {
         print "Trying message '" . $oMessage->subject . "'";
         $fileContent = $fileType = '';
         $geocoder = factory::create('geocoder');
         $postCode = $geocoder->extract_postcode($oMessage->subject);
         $fromName = null;
         $fromEmail = null;
         if (strpos($oMessage->from, '<')) {
             $split = split('<', $oMessage->from);
             //name - make sure name not an email address
             $fromName = trim($split[0]);
             if (valid_email($fromName)) {
                 $fromName = null;
             }
             //email
             $fromEmail = trim(str_replace('>', '', $split[1]));
         } else {
             $fromEmail = $oMessage->from;
         }
         $images = array();
         $messageStructure = imap_fetchstructure($oImap, $oMessage->msgno);
         if (isset($messageStructure->parts)) {
             $partNumber = 0;
             foreach ($messageStructure->parts as $oPart) {
                 $partNumber++;
                 if ($oPart->subtype == 'PLAIN' && !$postCode) {
                     $messageContent = imap_fetchbody($oImap, $oMessage->msgno, $partNumber);
                     if ($oPart->encoding == 4) {
                         $messageContent = quoted_printable_decode($messageContent);
                     }
                     $postCode = geocoder::extract_postcode($messageContent);
                 } elseif ($oPart->encoding == 3 && in_array($oPart->subtype, array('JPEG', 'PNG'))) {
                     $oImage = null;
                     $encodedBody = imap_fetchbody($oImap, $oMessage->msgno, $partNumber);
                     $fileContent = base64_decode($encodedBody);
                     $oImage = imagecreatefromstring($fileContent);
                     if (imagesx($oImage) > $this->min_import_size && imagesy($oImage) > $this->min_import_size) {
                         array_push($images, $oImage);
                     }
                     $fileType = strtolower($oPart->subtype);
                 }
             }
         }
         //add to the messages array
         array_push($validMessages, array('postcode' => $postCode, 'images' => $images, 'file_type' => $fileType, 'from_address' => $fromAddress, 'from_email' => $fromEmail, 'from_name' => $fromName));
         if ($delete) {
             imap_delete($oImap, $oMessage->msgno);
         }
     }
     imap_close($oImap, CL_EXPUNGE);
     $this->messages = $validMessages;
 }
 function getdata($host, $login, $password, $savedirpath)
 {
     $mbox = imap_open($host, $login, $password) or die("can't connect: " . imap_last_error());
     $message = array();
     $message["attachment"]["type"][0] = "text";
     $message["attachment"]["type"][1] = "multipart";
     $message["attachment"]["type"][2] = "message";
     $message["attachment"]["type"][3] = "application";
     $message["attachment"]["type"][4] = "audio";
     $message["attachment"]["type"][5] = "image";
     $message["attachment"]["type"][6] = "video";
     $message["attachment"]["type"][7] = "other";
     $buzon_destino = "cfdi";
     echo imap_createmailbox($mbox, imap_utf7_encode("{$buzon_destino}"));
     echo imap_num_msg($mbox);
     for ($jk = 1; $jk <= imap_num_msg($mbox); $jk++) {
         $structure = imap_fetchstructure($mbox, $jk);
         $parts = $structure->parts;
         $fpos = 2;
         for ($i = 1; $i < count($parts); $i++) {
             $message["pid"][$i] = $i;
             $part = $parts[$i];
             if (strtolower($part->disposition) == "attachment") {
                 $message["type"][$i] = $message["attachment"]["type"][$part->type] . "/" . strtolower($part->subtype);
                 $message["subtype"][$i] = strtolower($part->subtype);
                 $ext = $part->subtype;
                 $params = $part->dparameters;
                 $filename = $part->dparameters[0]->value;
                 if (!($ext == 'xml' or $ext == 'XML' or $ext == 'PDF' or $ext == 'pdf')) {
                     continue;
                 }
                 $mege = "";
                 $data = "";
                 $mege = imap_fetchbody($mbox, $jk, $fpos);
                 $data = $this->getdecodevalue($mege, $part->type);
                 $fp = fopen($filename, 'w');
                 fputs($fp, $data);
                 fclose($fp);
                 $fpos += 1;
                 /* Se mueve el archiv descargado al directorio de recibidos */
                 //                    rename($filename, $savedirpath.$filename);
                 //                    printf("\nSe movio el archivo $filename");
             }
         }
         $result = imap_fetch_overview($mbox, $jk);
         echo $result[0]->from;
         //            imap_mail_move($mbox, $jk, $buzon_destino);
         //imap_delete tags a message for deletion
         //    imap_delete($mbox,$jk);
     }
     // imap_expunge deletes all tagged messages
     //                    imap_expunge($mbox);
     imap_close($mbox);
 }
Example #7
1
 function inbox()
 {
     $this->msg_cnt = imap_num_msg($this->conn);
     echo "Number of emails read = " . $this->msg_cnt . "\n";
     /*$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)
     			); */
     $output = '<table>';
     $output .= '<tr><th>Subject</th><th>voucher</th><th>From</th><th>seen</th><th>type</th></tr>';
     $mails = imap_search($this->conn, 'FROM "*****@*****.**" SUBJECT "Confirm Hotel Booking"');
     //print_r($mails);
     for ($i = 0; $i <= sizeof($mails); $i++) {
         $header = imap_fetch_overview($this->conn, $mails[$i], 0);
         $body = imap_fetchbody($this->conn, $mails[$i], 1.1);
         $output .= '<tr>';
         $output .= '<td><span class="subject">' . $header[0]->subject . '</span> </td>';
         $output .= '<td><span class="from">' . $header[0]->from . '</span></td>';
         $output .= '<td><span class="voucher">' . $mails[0]->voucher . '</span></td>';
         $output .= '<td><span class="date">' . $header[0]->date . '</span></td>>';
         $output .= '<td><span class="toggler">' . ($header[0]->seen ? 'read' : 'unread') . '"></span></td>';
         $structure = imap_fetchstructure($this->conn, $mails[$i]);
         $output .= '<td><span class="type">' . $structure->type . '</span> </td>';
         $output .= '</tr>';
     }
     $output .= '</table>';
     echo $output . "\n";
 }
 public function listNew($user_id, $filter)
 {
     $inbox = $this->getInbox($user_id);
     if ($filter == '') {
         $filter = 'UNSEEN';
     } else {
         $filter = 'UNSEEN CC "t' . $filter . '@' . $this->domain . '"';
     }
     $emails = imap_search($inbox, $filter);
     $msgs = array();
     $ids = array();
     for ($start = count($emails); $start > 0;) {
         $start--;
         $ids[] = $emails[$start];
     }
     $overviews = imap_fetch_overview($inbox, implode(',', $ids));
     foreach ($overviews as $overview) {
         $msg_no = $overview->msgno;
         $message = isset($overview->subject) ? $overview->subject : imap_fetchbody($inbox, $msg_no, '1');
         $from = $overview->from;
         if (($pos = strpos($from, '<')) !== FALSE) {
             $sender_name = substr($from, 0, $pos);
             $pos2 = strpos($from, '@', $pos);
             $sender_id = substr($from, $pos + 2, $pos2 - $pos - 2);
         }
         $msgs[] = array('id' => $msg_no, 'sender_id' => $sender_id, 'sender_name' => $sender_name, 'date' => $overview->udate, 'msg' => json_decode($message), 'seen' => $overview->seen);
     }
     $unreads = imap_search($inbox, "UNSEEN");
     if ($unreads) {
         imap_setflag_full($inbox, implode(',', $unreads), '\\Seen');
     }
     return $msgs;
 }
Example #9
1
 /**
  * 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;
 }
Example #10
1
function retrieve_message($mbox, $messageid, $including = 0)
{
    $message = '';
    $structure = imap_fetchstructure($mbox, $messageid);
    if ($structure->type == 1) {
        // Если MULTI-PART письмо
        $message = imap_fetchbody($mbox, $messageid, $including + 1);
        $parameters = $structure->parts[$including]->parameters;
        $encoding = $structure->parts[$including]->encoding;
    } else {
        $message = imap_body($mbox, $messageid);
        $parameters = $structure->parameters;
        $encoding = $structure->encoding;
    }
    // if
    switch ($encoding) {
        // Декодируем
        case 0:
            // 7BIT
        // 7BIT
        case 1:
            // 8BIT
        // 8BIT
        case 2:
            // BINARY
            break;
        case 3:
            // BASE64
            $message = base64_decode($message);
            break;
        case 4:
            // QUOTED-PRINTABLE
            $message = quoted_printable_decode($message);
            break;
        case 5:
            // OTHER
        // OTHER
        default:
            // UNKNOWN
            return;
    }
    // switch
    $charset = '';
    for ($i = 0; $i < count($parameters); $i++) {
        if ($parameters[$i]->attribute == 'charset') {
            $charset = $parameters[$i]->value;
        }
    }
    return array($message, $charset);
}
 public static function emailDeliverFailBySubject($subject)
 {
     $mailcnf = "outlook.office365.com:993/imap/ssl/novalidate-cert";
     $username = MAILACCOUNT;
     $pw = MAILPASSWORD;
     $conn_str = "{" . $mailcnf . "}INBOX";
     $inbox = imap_open($conn_str, $username, $pw) or die('Cannot connect to mail: ' . imap_last_error());
     /* grab emails */
     $emails = imap_search($inbox, 'SUBJECT "Undeliverable: ' . $subject . '"');
     $failedInfo = [];
     /* if emails are returned, cycle through each... */
     if ($emails) {
         /* for every email... */
         foreach ($emails as $email_number) {
             /* get information specific to this email */
             $body = imap_fetchbody($inbox, $email_number, 2);
             $list = split('; ', $body);
             $sender = $list[2];
             $sender_email = explode("\n", $sender)[0];
             array_push($failedInfo, trim($sender_email));
         }
     }
     /* close the connection */
     imap_close($inbox);
     return $failedInfo;
 }
Example #12
0
 /**
  * Gets IMAP content
  *
  * @param string $imapHost
  * @param string $imapUser
  * @param string $imapPassword
  * @param \Swiftriver\Core\ObjectModel\Channel $channel
  *
  * @return $contentItems[]
  */
 private function GetIMAPContent($imapHost, $imapUser, $imapPassword, $channel)
 {
     $imapResource = imap_open("{" . $imapHost . "}INBOX", $imapUser, $imapPassword);
     //Open up unseen messages
     $imapEmails = imap_search($imapResource, strtoupper($channel->subType));
     $contentItems = array();
     if ($imapEmails) {
         //Put newest emails on top
         rsort($imapEmails);
         foreach ($imapEmails as $Email) {
             //Loop through each email and return the content
             $email_overview = imap_fetch_overview($imapResource, $Email, 0);
             $email_message = imap_fetchbody($imapResource, $Email, 2);
             $source_name = $imapUser;
             $source = \Swiftriver\Core\ObjectModel\ObjectFactories\SourceFactory::CreateSourceFromIdentifier($source_name);
             $source->name = $source_name;
             $source->parent = $channel->id;
             $source->type = $channel->type;
             $source->subType = $channel->subType;
             $item = \Swiftriver\Core\ObjectModel\ObjectFactories\ContentFactory::CreateContent($source);
             $item->text[] = new \Swiftriver\Core\ObjectModel\LanguageSpecificText(null, $email_overview[0]->subject, array($email_message));
             //the message
             $item->link = null;
             $item->date = $email_overview[0]->date;
             $contentItems[] = $item;
         }
         imap_close($imapResource);
         return $contentItems;
     }
     imap_close($imapResource);
     return null;
 }
Example #13
0
function mail_decode_part($connection, $message_number, $part, $prefix)
{
    $attachment = array();
    if ($part->ifdparameters) {
        foreach ($part->dparameters as $object) {
            $attachment[strtolower($object->attribute)] = $object->value;
            if (strtolower($object->attribute) == 'filename') {
                $attachment['is_attachment'] = true;
                $attachment['filename'] = $object->value;
            }
        }
    }
    if ($part->ifparameters) {
        foreach ($part->parameters as $object) {
            $attachment[strtolower($object->attribute)] = $object->value;
            if (strtolower($object->attribute) == 'name') {
                $attachment['is_attachment'] = true;
                $attachment['name'] = $object->value;
            }
        }
    }
    $attachment['data'] = imap_fetchbody($connection, $message_number, $prefix);
    if ($part->encoding == 3) {
        // 3 = BASE64
        $attachment['data'] = base64_decode($attachment['data']);
    } elseif ($part->encoding == 4) {
        // 4 = QUOTED-PRINTABLE
        $attachment['data'] = quoted_printable_decode($attachment['data']);
    }
    return $attachment;
}
function getpart($mbox, $mid, $p, $partno, $charset, $htmlmsg, $plainmsg, $attachments)
{
    // $partno = '1', '2', '2.1', '2.1.3', etc for multipart, 0 if simple
    // DECODE DATA
    if ($p->encoding != 3 || $partno < 2) {
        $data = $partno ? imap_fetchbody($mbox, $mid, $partno, FT_UID) : imap_body($mbox, $mid, FT_UID);
    }
    // simple
    // Any part may be encoded, even plain text messages, so check everything.
    if ($p->encoding == 4) {
        $data = quoted_printable_decode($data);
    } elseif ($p->encoding == 3) {
        $data = base64_decode($data);
    }
    // PARAMETERS
    // get all parameters, like charset, filenames of attachments, etc.
    $params = array();
    if ($p->parameters) {
        foreach ($p->parameters as $x) {
            $params[strtolower($x->attribute)] = $x->value;
        }
    }
    if ($p->dparameters) {
        foreach ($p->dparameters as $x) {
            $params[strtolower($x->attribute)] = $x->value;
        }
    }
    // ATTACHMENT
    // Any part with a filename is an attachment,
    // so an attached text file (type 0) is not mistaken as the message.
    if ($params['filename'] || $params['name']) {
        // filename may be given as 'Filename' or 'Name' or both
        $filename = $params['filename'] ? $params['filename'] : $params['name'];
        // filename may be encoded, so see imap_mime_header_decode()
        $attachments[$filename] = $data;
        // this is a problem if two files have same name
    }
    // TEXT
    if ($p->type == 0 && $data) {
        // Messages may be split in different parts because of inline attachments,
        // so append parts together with blank row.
        if (strtolower($p->subtype) == 'plain') {
            $plainmsg .= trim($data) . "\n\n";
        } else {
            $htmlmsg .= $data . "<br /><br />";
        }
        $charset = $params['charset'];
        // assume all parts are same charset
    } elseif ($p->type == 2 && $data) {
        $plainmsg .= $data . "\n\n";
    }
    // SUBPART RECURSION
    if ($p->parts) {
        foreach ($p->parts as $partno0 => $p2) {
            list($charset, $htmlmsg, $plainmsg, $attachments) = getpart($mbox, $mid, $p2, $partno . '.' . ($partno0 + 1), $charset, $htmlmsg, $plainmsg, $attachments);
        }
        // 1.2, 1.2.1, etc.
    }
    return array($charset, $htmlmsg, $plainmsg, $attachments);
}
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
}
Example #16
0
 /**
  * Gets IMAP content
  *
  * @param string $imapHost
  * @param string $imapUser
  * @param string $imapPassword
  * @param \Swiftriver\Core\ObjectModel\Channel $channel
  *
  * @return $contentItems[]
  */
 private function GetIMAPContent($imapHost, $imapUser, $imapPassword, $channel)
 {
     $imapResource = imap_open("{" . $imapHost . "}INBOX", $imapUser, $imapPassword);
     //Open up unseen messages
     $search = $channel->lastSuccess == null ? "UNSEEN" : "UNSEEN SINCE " . \date("Y-m-d", $channel->lastSuccess);
     $imapEmails = imap_search($imapResource, $search);
     $contentItems = array();
     if ($imapEmails) {
         //Put newest emails on top
         rsort($imapEmails);
         foreach ($imapEmails as $Email) {
             //Loop through each email and return the content
             $email_overview = imap_fetch_overview($imapResource, $Email, 0);
             if (strtotime(reset($email_overview)->date) < $channel->lastSuccess) {
                 continue;
             }
             $email_header_info = imap_header($imapResource, $Email);
             $email_message = imap_fetchbody($imapResource, $Email, 1);
             $source_name = \reset($email_overview)->from;
             $source = \Swiftriver\Core\ObjectModel\ObjectFactories\SourceFactory::CreateSourceFromIdentifier($source_name);
             $source->name = $source_name;
             $source->parent = $channel->id;
             $source->type = $channel->type;
             $source->subType = $channel->subType;
             $item = \Swiftriver\Core\ObjectModel\ObjectFactories\ContentFactory::CreateContent($source);
             $item->text[] = new \Swiftriver\Core\ObjectModel\LanguageSpecificText(null, $email_overview[0]->subject, array($email_message));
             //the message
             $item->link = null;
             $item->date = $email_header_info->udate;
             $contentItems[] = $item;
         }
     }
     imap_close($imapResource);
     return $contentItems;
 }
Example #17
0
 function getPart($partNumber, $encoding)
 {
     $data = imap_fetchbody($this->connection, $this->messageNumber, $partNumber, FT_UID);
     switch ($encoding) {
         case 0:
             return $data;
             // 7BIT
         // 7BIT
         case 1:
             return $data;
             // 8BIT
         // 8BIT
         case 2:
             return $data;
             // BINARY
         // BINARY
         case 3:
             return base64_decode($data);
             // BASE64
         // BASE64
         case 4:
             return quoted_printable_decode($data);
             // QUOTED_PRINTABLE
         // QUOTED_PRINTABLE
         case 5:
             return $data;
             // OTHER
     }
 }
 function fetchbody($stream, $msgnr, $partnr, $flags = 0)
 {
     // do we force use of msg UID's
     if ($this->force_msg_uids == True && !($flags & FT_UID)) {
         $flags |= FT_UID;
     }
     return imap_fetchbody($stream, $msgnr, $partnr, $flags);
 }
	private function fetchContent( Message $message , $subtype , $msgNum , $part , array $parameters = array() ) {
		$content = base64_decode( imap_fetchbody( ImapState::$resource , $msgNum , $part ) );

		foreach ( $parameters as $parameter ) {
			if ( $parameter->attribute == 'CHARSET' ) {
				$content = mb_convert_encoding( $content , 'UTF-8' , $parameter->value );
			}
		}

		$message->setContent( $subtype , $content );
	}
Example #20
0
function CheckMail()
{
    echo "===========================\n";
    echo " CHECK MAIL\n";
    echo "===========================\n";
    global $rawDIR, $nowGradeFile, $now;
    // 	$outFile=fopen($nowGradeFile,"w");
    $hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
    $username = "******";
    $password = '******';
    /* try to connect */
    $inbox = imap_open($hostname, $username, $password) or die('Cannot connect to Gmail: ' . imap_last_error());
    /* grab emails */
    // 	$emails = imap_search($inbox, 'ALL', '*****@*****.**');
    $emails = imap_search($inbox, 'FROM noreply@wcasd.net');
    /* if emails are returned, cycle through each... */
    if ($emails) {
        /* begin output var */
        $output = '';
        /* put the newest emails on top */
        // 		rsort($emails);
        /* for every email... */
        foreach ($emails as $email_number) {
            /* get information specific to this email */
            $overview = imap_fetch_overview($inbox, $email_number, 0);
            // 			if ( $overview[0]->from == "*****@*****.**" && $overview[0]->seen == 0 ) {
            // 			if ( $overview[0]->from == "*****@*****.**" ) {
            $output .= "Number: {$email_number}\n";
            $output .= "From: " . $overview[0]->from . "\n";
            $output .= "Subject: " . $overview[0]->subject . "\n";
            $output .= "Seen: " . $overview[0]->seen . "\n";
            $output .= "Date: " . $overview[0]->date . "\n";
            $message = imap_fetchbody($inbox, $email_number, 1);
            // 				$message = imap_body($inbox, $email_number, 'FT_PEEK');
            // 				echo "MESSAGE: ". $message;
            $outFile = fopen($nowGradeFile, "w");
            fwrite($outFile, $message);
            fclose($outFile);
            if (file_exists($nowGradeFile)) {
                echo "Wrote {$nowGradeFile}.\n";
            } else {
                echo "Failed to write {$nowGradeFile}.\n";
            }
            // 				imap_setflag_full($inbox, $email_number, 'unseen');
            // 				imap_mail_move($inbox, "$email_number", 'School');
            // 				break;
            // 			}
        }
    }
    /* close the connection */
    imap_close($inbox);
    echo "{$output}\n";
    exit;
}
Example #21
0
 public function fetch_body($email_number = '0', $section = '1', $options = '0')
 {
     //debug::output("Fetching Body...");
     $body = imap_fetchbody($this->imap, $email_number, $section, $options);
     if (empty($body)) {
         debug::output("No Email in body...");
         //throw new emailException(imap_last_error($this->imap),imap_errors($this->imap));
     } else {
         return $body;
     }
 }
Example #22
0
function parse_message_fetch_body($connection, &$part, $message_number, $id, $option)
{
    $body = imap_fetchbody($connection, $message_number, $id, $option);
    if ($part->encoding == ENCBASE64) {
        $body = base64_decode($body);
    } else {
        if ($part->encoding == ENCQUOTEDPRINTABLE) {
            $body = quoted_printable_decode($body);
        }
    }
    return $body;
}
Example #23
0
 private function decodeMailAtachment($i)
 {
     $wiad = imap_fetchbody($this->mbox, $this->nummesage, $i);
     $wiad = base64_decode($wiad);
     $wiad = imagecreatefromstring($wiad);
     $info = imap_fetchmime($this->mbox, $this->nummesage, $i);
     $info = $this->attachmentslInfo($this->mbox, $this->nummesage);
     $wiad = imap_fetchbody($this->mbox, $this->nummesage, $i);
     $wiad = base64_decode($wiad);
     $wiad = imagecreatefromstring($wiad);
     return $wiad;
 }
Example #24
0
 public function getBody($emails, $part, $subPart)
 {
     $aBodies = array();
     foreach ($emails as $email_id) {
         $body = imap_fetchbody($this->imap_client, $email_id, $subPart);
         if ($body == "") {
             $body = imap_fetchbody($this->imap_client, $email_id, $part);
         }
         array_push($aBodies, $body);
     }
     return $aBodies;
 }
Example #25
0
 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;
     }
 }
Example #26
0
 /**
  *
  * @param time $fromDate
  * @param int $limit
  * @return Email[]
  */
 public function GetEmails($fromDate = null, $limit = -1)
 {
     //try to open the inbox
     $inbox = imap_open($this->hostname, $this->username, $this->password);
     //get the emails
     $emails = imap_search($inbox, 'ALL');
     if (!$emails) {
         //do something?
     }
     //put the newest email first
     rsort($emails);
     //set up the return array
     $returnEmails = array();
     $counter = 0;
     foreach ($emails as $emailId) {
         //check we are not over our limit
         if ($limit > 0 && $counter > $limit) {
             //if we are then stop adding emails
             break;
         }
         //get the email overview
         $overview = imap_fetch_overview($inbox, $emailId, 0);
         //get the date of the email
         $date = $overview[0]->date;
         //If a from date is supplied
         if (isset($fromDate)) {
             //check if this is within the date
             if (strtotime($date) < $fromDate) {
                 //if it is then skip it.
                 continue;
             }
         }
         //get the email message
         $message = imap_fetchbody($inbox, $emailId, 2);
         //Create a new email object
         $returnEmail = new Email();
         //collect the data for imap
         $returnEmail->date = $date;
         $returnEmail->message = $message;
         $returnEmail->read = $overview[0]->seen;
         $returnEmail->sender = $overview[0]->from;
         $returnEmail->subject = $overview[0]->subject;
         //Add the email to the return array
         $returnEmails[] = $returnEmail;
         //increment the counter
         $counter++;
     }
     //Close the imap connection
     imap_close($inbox);
     //return the emails
     return $returnEmails;
 }
/**
 * Liefert ein Array mit den Texten von, je nach 3. Parameter, allen oder nur den ungelesenen Mails
 */
function getMailMessages($inbox, $emails, $onlyUnread = false)
{
    $messages = array();
    if ($emails) {
        foreach ($emails as $email_number) {
            $message = imap_fetchbody($inbox, $email_number, 2);
            if (!$overview[0]->seen || !$onlyUnread) {
                $messages[count($messages)] = $message;
            }
        }
    }
    return $message;
}
Example #28
0
 private function getMessageBody($email, $messageId, callable $process, $parameter)
 {
     foreach ([1, 2] as $option) {
         $data = $process(imap_fetchbody($this->connections[$email], $messageId, $option));
         if (!empty($data)) {
             if ('charset' === strtolower($parameter->attribute) && 'utf-8' !== strtolower($parameter->value)) {
                 $data = iconv($parameter->value, 'utf-8', $data);
             }
             return quoted_printable_decode($data);
         }
     }
     return '';
 }
Example #29
0
 private function _getMailList()
 {
     $mbox = imap_open(sprintf("{%s:%d/imap/ssl}INBOX", $this->_server, $this->_port), $this->_email, $this->_password);
     $mailList = imap_search($mbox, 'ALL');
     $bodyList = array();
     if (is_array($mailList)) {
         foreach ($mailList as $num) {
             $body = imap_fetchbody($mbox, $num, "1");
             array_push($bodyList, $body);
             imap_delete($mbox, $num);
         }
     }
     return $bodyList;
 }
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();
        }
    }
}