function getAttachments($imap, $mailNum, $part, $partNum) { $attachments = array(); if (isset($part->parts)) { foreach ($part->parts as $key => $subpart) { if ($partNum != "") { $newPartNum = $partNum . "." . ($key + 1); } else { $newPartNum = $key + 1; } $result = getAttachments($imap, $mailNum, $subpart, $newPartNum); if (count($result) != 0) { array_push($attachments, $result); } } } else { if (isset($part->disposition)) { if ($part->disposition == "ATTACHMENT") { $partStruct = imap_bodystruct($imap, $mailNum, $partNum); $attachmentDetails = array("name" => $part->dparameters[0]->value, "partNum" => $partNum, "enc" => $partStruct->encoding); return $attachmentDetails; } } } return $attachments; }
/** * Get body structure * * @return mixed */ public function getMessageBodyStruct($pos, $no, $uid = 0) { return imap_bodystruct($this->_mailbox_link, $pos, $no, $uid); }
public function getBodystruct($uid, $part) { return $this->bodystruct = imap_bodystruct($this->mbox, $this->getMsgno($uid), $part); }
/** * This function returns an object containing the raw headers of the message. * * @param string $partIdentifier * @return string */ protected function setRawBody($partIdentifier = null) { if (isset($partIdentifier)) { $body = imap_fetchbody($this->imapStream, $this->uid, $partIdentifier, FT_UID | FT_PEEK); $this->rawBody[$partIdentifier] = ['structure' => imap_bodystruct($this->imapStream, imap_msgno($this->imapStream, $this->uid), $partIdentifier), 'body' => $body]; } else { $this->rawBody = $body = imap_body($this->imapStream, $this->uid, FT_UID | FT_PEEK); } return $body; }
throw new Exception($err); } $emails = imap_search($inbox, 'ALL UNSEEN'); if (!$emails) { return; } foreach ($emails as $msg_number) { $header = imap_headerinfo($inbox, $msg_number); $structure = imap_fetchstructure($inbox, $msg_number); $text = ""; $attachments = array(); // Use text from non-multipart messages directly if (empty($structure->parts)) { // Get message body $text = imap_fetchbody($inbox, $msg_number, 1); $part = imap_bodystruct($inbox, $msg_number, 1); // Decode body if ($part->encoding == 4) { $text = imap_qprint($text); } elseif ($part->encoding == 3) { $text = imap_base64($text); } } // Load message parts for multipart messages if (!empty($structure->parts)) { foreach ($structure->parts as $part_number => $part) { // Handle plaintext if ($part->type === 0 && !trim($text)) { $text = imap_fetchbody($inbox, $msg_number, $part_number + 1); // Decode body if ($part->encoding == 4) {
function saveAttachment($uid, $partNum, $encoding) { $partStruct = imap_bodystruct($this->stream, imap_msgno($this->stream, $uid), $partNum); $message = imap_fetchbody($this->stream, $uid, $partNum, FT_UID); switch ($encoding) { case 0: case 1: $message = imap_8bit($message); break; case 2: $message = imap_binary($message); break; case 3: $message = imap_base64($message); break; case 4: $message = quoted_printable_decode($message); break; } return $message; }
} else { if ($headrs->deleted) { $delstyle = " text-decoration:line-through;opacity:.35; "; } else { $delstyle = ""; } } $mail_headerinfo = @imap_headerinfo($mbox, $headrs->msgno); $mail_senddate = $mail_headerinfo->MailDate; $mailstruct = imap_fetchstructure($mbox, $headrs->msgno); $selectBoxDisplay = ""; $att = ""; $contentParts = count($mailstruct->parts); if ($contentParts >= 2) { for ($i = 2; $i <= $contentParts; $i++) { $att[$i - 2] = imap_bodystruct($mbox, $headrs->msgno, $i); } for ($k = 0; $k < sizeof($att); $k++) { $p = $att[$k]; if (count($p->dparameters) > 0) { foreach ($p->dparameters as $dparam) { if (strtoupper($dparam->attribute) == 'NAME' || strtoupper($dparam->attribute) == 'FILENAME') { $selectBoxDisplay[$k] = $dparam->value; } } } //if no filename found if ($filename == '') { // if there are any parameters present in this part if (count($p->parameters) > 0) { foreach ($p->parameters as $param) {
{$body} </div></li> END; } else { $body = str_replace('<a ', "<a target=\"_blank\" ", $body); $body = str_replace('<A ', "<a target=\"_blank\" ", $body); echo $body; } $struct = imap_fetchstructure($mbox, $msgno); $contentParts = count($struct->parts); if ($contentParts >= 2) { for ($i = 2; $i <= $contentParts; $i++) { $att[$i - 2] = imap_bodystruct($mbox, $msgno, $i); } for ($k = 0; $k < sizeof($att); $k++) { /*if ($att[$k]->parameters[0]->value == "us-ascii" || $att[$k]->parameters[0]->value == "US-ASCII") { if ($att[$k]->parameters[1]->value != "") { $selectBoxDisplay[$k] = imap_utf8_workaround($att[$k]->parameters[1]->value); } } elseif ($att[$k]->parameters[0]->value != "iso-8859-1" && $att[$k]->parameters[0]->value != "ISO-8859-1") { $selectBoxDisplay[$k] = imap_utf8_workaround($att[$k]->parameters[0]->value); }*/ $p = $att[$k]; if (count($p->dparameters) > 0) { foreach ($p->dparameters as $dparam) { if (strtoupper($dparam->attribute) == 'NAME' || strtoupper($dparam->attribute) == 'FILENAME') { $selectBoxDisplay[$k] = $dparam->value; }
/** * Retrieve body part, and if it's file write it to filesystem * * @param integer $message_id * @param string $body_part * @param string $file_path * @return mixed */ function getBodyPart($message_id, $body_part, $encoding, $file_path = false) { if ($file_path) { if (!MM_CAN_DOWNLOAD_LARGE_ATTACHMENTS) { $structure = imap_bodystruct($this->getConnection(), $message_id, $body_part); if (!instance_of($structure, 'stdClass')) { return false; } // if // if attachment is larger than FAIL_SAFE_IMAP_ATTACHMENT_SIZE_MAX, don't download it if ($structure->bytes > FAIL_SAFE_IMAP_ATTACHMENT_SIZE_MAX) { return false; } // if } // if $savebody_result = imap_savebody_alt($this->getConnection(), $file_path, $message_id, $body_part); if (!$savebody_result) { return false; } // if $temporary_file = $file_path . '_temp'; switch ($encoding) { case 'base64': $decoding_result = base64_decode_file($file_path, $temporary_file); if ($decoding_result) { @unlink($file_path); rename($temporary_file, $file_path); return true; } else { @unlink($file_path); @unlink($temporary_file); return false; } break; case 'quoted-printable': $decoding_result = quoted_printable_decode_file($file_path, $temporary_file); if ($decoding_result) { @unlink($file_path); rename($temporary_file, $file_path); return true; } else { @unlink($file_path); @unlink($temporary_file); return false; } break; } // switch return true; } else { $result = imap_fetchbody($this->getConnection(), $message_id, $body_part); switch ($encoding) { case 'base64': return imap_base64($result); break; case 'quoted-printable': return imap_qprint($result); break; default: return $result; break; } // switch } // if }
function getInlineAttach($partNum, $encoding) { $this->structure = @imap_bodystruct($this->paloImap, @imap_msgno($this->paloImap, $this->uid), $partNum); $filename = $this->structure->dparameters[0]->value; $message = @imap_fetchbody($this->paloImap, $this->uid, $partNum, FT_UID); $message = $this->decodeAttachData($encoding, $message); header("Content-Type: application/octet-stream"); header("Content-Disposition: inline; filename=" . $filename); echo $message; }
function processBounce($pos, $type, $header = null) { if (!empty($header)) { $md5header = md5($header); } else { $md5header = null; } if ($type == 'DSN') { // first part of DSN (Delivery Status Notification), human-readable explanation $dsn_msg = imap_fetchbody($this->_mailbox_link, $pos, "1"); $dsn_msg_structure = imap_bodystruct($this->_mailbox_link, $pos, "1"); if ($dsn_msg_structure->encoding == 3) { $dsn_msg = base64_decode($dsn_msg); } // second part of DSN (Delivery Status Notification), delivery-status $dsn_report = imap_fetchbody($this->_mailbox_link, $pos, "2"); // process bounces by rules $result = bmhDSNRules($dsn_msg, $dsn_report, $this->debug_dsn_rule); } elseif ($type == 'BODY') { $structure = imap_fetchstructure($this->_mailbox_link, $pos); switch ($structure->type) { case 0: // Content-type = text // Content-type = text case 2: // Content-type = message $body = imap_body($this->_mailbox_link, $pos); if ($structure->encoding == 3) { $body = base64_decode($body); } $body = substr($body, 0, 1000); $result = bmhBodyRules($body, $structure, $this->debug_body_rule); break; case 1: // Content-type = multipart $body = imap_fetchbody($this->_mailbox_link, $pos, "1"); // TRICKY : detect encoding and decode // only handle base64 right now if ($structure->parts[0]->encoding == 3) { $body = base64_decode($body); } $body = substr($body, 0, 1000); $result = bmhBodyRules($body, $structure, $this->debug_body_rule); break; default: // unsupport Content-type $this->output("The No. {$pos} is unsupport Content-Type:{$structure->type}", VERBOSE_REPORT); return false; } } else { // internal error $this->error_msg = 'Internal Error: unknown type'; return false; } $result['rule_type'] = $type; if (!empty($header)) { if (preg_match("/Subject:((?:[^\n]|\n[\t ])+)(?:\n[^\t ]|\$)/is", $header, $match)) { $result['subject'] = trim($match[1]); } if (preg_match("/Date:[\t ]*(.*)/i", $header, $match)) { $result['date'] = trim($match[1]); } if (preg_match("/From:((?:[^\n]|\n[\t ])+)(?:\n[^\t ]|\$)/is", $header, $match)) { $addresses = imap_rfc822_parse_adrlist($match[1], '???'); if (!empty($addresses) && is_array($addresses)) { $result['from'] = $addresses[0]->mailbox . '@' . $addresses[0]->host; } } } // last chance for unmatched rules if ($result['rule_no'] == '0000') { $result = bmhOtherRules($result); } $result['md5header'] = $md5header; // log the result if wanted if (!empty($this->log_function) && function_exists($this->log_function)) { call_user_func($this->log_function, $result); $this->c_log++; } // call user function for unmatched rules if ($result['rule_no'] == '0000') { if (!empty($this->unmatched_function) && function_exists($this->unmatched_function)) { return call_user_func($this->unmatched_function, $result); } return false; } if ($this->testmode) { $this->output(print_r($result, true)); return false; } // match a rule, take bounce action if (!empty($this->action_function) && function_exists($this->action_function)) { return call_user_func($this->action_function, $result); } return true; }
public function getMessagePart($msgno, $partObj, $partno = 0) { echo "<br /><hr /><br />getMessagePart({$msgno},part,{$partno})<br />"; // If partno is 0 then fetch body as a single part message //echo " imap_fetchbody($this->hconnection, $msgno, $partno, FT_PEEK); "; // echo "<hr /> partno=";//.(int)$partno." "; // var_dump($partno); // echo "<br /> msgno=".(int)$msgno." "; // var_dump($msgno); if ($partno) { $data = imap_fetchbody($this->hconnection, $msgno, $partno, FT_PEEK); } else { $data = imap_body($this->hconnection, $msgno, FT_PEEK); } // $data = ($partno) ? imap_fetchbody($conn, $messageId, $partno) : imap_body($conn, $messageId); // Any part may be encoded, even plain text messages, so decoding it echo " encoding " . $partObj->encoding . "\n"; if ($partObj->encoding == 4) { $data = quoted_printable_decode($data); } elseif ($partObj->encoding == 3) { $data = base64_decode($data); } // Collection all parameters, like name, filenames of attachments, etc. $params = array(); if ($partObj->parameters) { foreach ((array) $partObj->parameters as $x) { echo " attribute " . $x->attribute . "\n"; $params[strtolower($x->attribute)] = $x->value; if ($x->attribute == 'charset' || $x->attribute == 'CHARSET') { echo " charset " . $x->value . "\n"; if (in_array(strtolower($x->value), array('windows-1250', 'iso-8859-2'))) { echo '[BODY : ENCODING] presented: ' . $x->value . ' => encoding to utf-8' . "\n"; $data = iconv($x->value, 'UTF-8', $data); } if (in_array(strtolower($x->value), array('us-ascii', 'default'))) { require_once LIB_PATH . 'mail/Mail_Encoding.php'; $detected = Mail_Encoding::detect($data); if ($detected != 'utf-8') { echo '[BODY : ENCODING] presented: ' . $x->value . ' , detected: ' . $detected . ' => encoding to utf-8' . "\n"; $data = iconv($detected, 'UTF-8', $data); } } } } } if ($partObj->dparameters) { foreach ((array) $partObj->dparameters as $x) { $params[strtolower($x->attribute)] = $x->value; } } if ($partObj->id) { if ($partObj->type == 5) { // IMAGE $extension = strtolower($partObj->subtype); $params['filename'] = md5($partObj->id) . '.' . $extension; } } // Any part with a filename is an attachment, if ($params['filename'] || $params['name']) { // Filename may be given as 'Filename' or 'Name' or both $filename = $params['filename'] ? $params['filename'] : $params['name']; if (empty($this->attachments[$filename])) { $this->attachments[$filename] = $data; } } // Processing plain text message if ($partObj->type == 0 && $data) { // Messages may be split in different parts because of inline attachments, // so append parts together with blank row. if (strtolower($partObj->subtype) == 'plain' || strtolower($partObj->subtype) == 'text/plain') { $this->plainBody = trim($data); // echo "<br /><br /><br /><hr /><br />PLAINBODY<br />$data<br />ENDPLAINBODY<hr /><br />"; } else { $this->htmlBody = $data; // echo "<br /><br /><br /><hr /><br />HTMLBODY<br />$data<br />ENDHTMLBODY<hr /><br />"; } } elseif ($partObj->type == 2 && $data) { $this->plainBody .= $data; } // Here is recursive call for subpart of the message if ($partObj->parts) { foreach ((array) $partObj->parts as $partno2 => $part2) { $this->getMessagePart($msgno, $part2, $partno . '.' . ($partno2 + 1)); } if ($partObj->subtype == 'RFC822') { echo '[RFC PART] detected: ' . $partno . "\n"; for ($i = sizeof($partObj->parts) + 1;; $i++) { $partObj2 = imap_bodystruct($this->hconnection, $msgno, $partno . '.' . $i); if (!empty($partObj2)) { $this->getMessagePart($msgno, $partObj2, $partno . '.' . $i); } else { break; } } } } }
/** * returnMessageBodyStructureObj * @see http://www.php.net/manual/en/function.imap-bodystruct.php * @param $messageNumber(int),part(int) * @return object */ private function returnBodyStructureObj($messageNumber, $part) { return imap_bodystruct($this->stream, $messageNumber, $part); }
exit("TEST FAILED: Unable to create test mailbox\n"); } echo "\nGet and validate structure of body part 1\n"; $m = imap_bodystruct($imap_stream, 1, "1"); $mandatoryFields = array('ifsubtype', 'ifdescription', 'ifid', 'ifdisposition', 'ifdparameters', 'ifparameters'); foreach ($mandatoryFields as $mf) { if (isValid($m->{$mf})) { echo "{$mf} is 0 or 1\n"; } else { echo "{$mf} FAIL\n"; } } if (is_array($m->parameters)) { echo "parameters is an array\n"; } echo "\nTry to get part 4!\n"; var_dump(imap_bodystruct($imap_stream, 1, "4")); imap_close($imap_stream); function isValid($param) { if ($param == 0 || $param == 1) { $result = true; } else { $result = false; } return $result; } ?> ===Done=== <?php require_once 'clean.inc';
/** * Returns an array containing all files attached to message * * @param int $msgno The index of the message to retrieve * @param bool $include_raw_data The raw data is the actual contents of the attachment file. Setting this to FALSE will allow you to display the name, size, type, etc of all attachments without actually downloading the contents of the files. Use GetAttachmentRawData to retrieve the raw data for an individual attachment. * @return array An array of attachments * */ function GetAttachments($msgno, $include_raw_data = true) { $struct = imap_fetchstructure($this->mbox, $msgno); $contentParts = count($struct->parts); $attachments = array(); if ($contentParts >= 2) { for ($i = 2; $i <= $contentParts; $i++) { $att[$i - 2] = imap_bodystruct($this->mbox, $msgno, $i); // these extra bits help us later... $att[$i - 2]->x_msg_id = $msgno; $att[$i - 2]->x_part_id = $i; } for ($k = 0; $k < sizeof($att); $k++) { if (strtolower($att[$k]->parameters[0]->value) == "us-ascii" && $att[$k]->parameters[1]->value != "") { $attachments[$k] = $this->_getPartFromStruct($att[$k], $include_raw_data); } elseif (strtolower($att[$k]->parameters[0]->value) != "iso-8859-1") { $attachments[$k] = $this->_getPartFromStruct($att[$k], $include_raw_data); } } } return $attachments; }
function email_to_commsy($mbox, $msgno) { global $environment; global $portal_id_array; global $c_email_upload_email_account; $translator = $environment->getTranslationObject(); $struct = imap_fetchstructure($mbox, $msgno); $header = imap_headerinfo($mbox, $msgno); $sender = $header->from[0]->mailbox . '@' . $header->from[0]->host; $subject = $header->subject; #$body = imap_fetchbody($mbox,$msgno,1); // just use the plain part of the e-mail $body_plain = get_part($mbox, $msgno, "TEXT/PLAIN"); $body_html = get_part($mbox, $msgno, "TEXT/HTML"); $body_is_plain = true; if (!empty($body_plain)) { $body = $body_plain; } else { $body_is_plain = false; $body = $body_html; } // get additional Information from e-mail body $translator->setSelectedLanguage('de'); $translation['de']['password'] = $translator->getMessage('EMAIL_TO_COMMSY_PASSWORD'); $translation['de']['account'] = $translator->getMessage('EMAIL_TO_COMMSY_ACCOUNT'); $translator->setSelectedLanguage('en'); $translation['en']['password'] = $translator->getMessage('EMAIL_TO_COMMSY_PASSWORD'); $translation['en']['account'] = $translator->getMessage('EMAIL_TO_COMMSY_ACCOUNT'); $account = ''; $secret = ''; $body = preg_replace('/\\r\\n|\\r/', "\n", $body); $body_array = explode("\n", $body); $temp_body = array(); $with_footer = false; $footer_line = 0; $index = 0; foreach ($body_array as $body_line) { if (strip_tags($body_line) == '-- ') { // start of e-mail signature $with_footer = true; $footer_line = $index; } $index++; } $index = 0; $secret_found = false; $account_found = false; foreach ($body_array as $body_line) { if ($with_footer and $index == $footer_line) { break; } if (!empty($body_line)) { $body_line = strip_tags($body_line); if (stristr($body_line, $translation['de']['account']) and !$account_found) { $temp_body_line = str_ireplace($translation['de']['account'] . ':', '', $body_line); $temp_body_line_array = explode(' ', trim($temp_body_line)); $account = $temp_body_line_array[0]; $account_found = true; } else { if (stristr($body_line, $translation['en']['account']) and !$account_found) { $temp_body_line = str_ireplace($translation['en']['account'] . ':', '', $body_line); $temp_body_line_array = explode(' ', trim($temp_body_line)); $account = $temp_body_line_array[0]; $account_found = true; } else { if (stristr($body_line, $translation['de']['password']) and !$secret_found) { $temp_body_line = str_ireplace($translation['de']['password'] . ':', '', $body_line); $temp_body_line_array = explode(' ', trim($temp_body_line)); $secret = $temp_body_line_array[0]; $secret_found = true; } else { if (stristr($body_line, $translation['en']['password']) and !$secret_found) { $temp_body_line = str_ireplace($translation['en']['password'] . ':', '', $body_line); $temp_body_line_array = explode(' ', trim($temp_body_line)); $secret = $temp_body_line_array[0]; $secret_found = true; } else { $temp_body[] = $body_line; } } } } } else { $temp_body[] = $body_line; } $index++; } $body = implode("\n", $temp_body); foreach ($portal_id_array as $portal_id) { $environment->setCurrentPortalID($portal_id); $user_manager = $environment->getUserManager(); $user_manager->setContextArrayLimit($portal_id); $user_manager->setEMailLimit($sender); $user_manager->select(); $user_list = $user_manager->get(); $user = $user_list->getfirst(); $found_users = array(); while ($user) { if ($account != '') { if ($account == $user->getUserID()) { $found_users[] = $user; } } else { $found_users[] = $user; } $user = $user_list->getnext(); } foreach ($found_users as $found_user) { $private_room_user = $found_user->getRelatedPrivateRoomUserItem(); $private_room = $private_room_user->getOwnRoom(); $translator->setSelectedLanguage($private_room->getLanguage()); if ($private_room->getEmailToCommSy()) { $email_to_commsy_secret = $private_room->getEmailToCommSySecret(); $result_mail = new cs_mail(); $result_mail->set_to($sender); $result_mail->set_from_name('CommSy'); // $result_mail->set_from_email('*****@*****.**'); $errors = array(); if ($secret == $email_to_commsy_secret) { $private_room_id = $private_room->getItemID(); $files = array(); if ($struct->subtype == 'PLAIN') { } else { if ($struct->subtype == 'MIXED') { // with attachment $contentParts = count($struct->parts); if ($contentParts >= 2) { for ($i = 2; $i <= $contentParts; $i++) { $att[$i - 2] = imap_bodystruct($mbox, $msgno, $i); } for ($k = 0; $k < sizeof($att); $k++) { $strFileName = $att[$k]->dparameters[0]->value; $strFileType = strrev(substr(strrev($strFileName), 0, 4)); $fileContent = imap_fetchbody($mbox, $msgno, $k + 2); $file = getFile($strFileType, $strFileName, $fileContent); // copy file to temp $temp_file = 'var/temp/' . $strFileName . '_' . getCurrentDateTimeInMySQL(); file_put_contents($temp_file, $file); $temp_array = array(); $temp_array['name'] = utf8_encode($strFileName); $temp_array['tmp_name'] = $temp_file; $temp_array['file_id'] = $temp_array['name'] . '_' . getCurrentDateTimeInMySQL(); $temp_array['file_size'] = filesize($temp_file); $files[] = $temp_array; } } } } $environment->setCurrentContextID($private_room_id); $environment->setCurrentUser($private_room_user); $environment->unsetLinkModifierItemManager(); $material_manager = $environment->getMaterialManager(); $material_item = $material_manager->getNewItem(); $material_item->setTitle(trim(str_replace($email_to_commsy_secret . ':', '', $subject))); $material_item->setDescription($body); // attach files to the material $file_manager = $environment->getFileManager(); $file_manager->setContextLimit($private_room_id); $portal_item = $environment->getCurrentPortalItem(); $portal_max_file_size = $portal_item->getMaxUploadSizeInBytes(); $file_id_array = array(); $error['files_to_large'] = array(); foreach ($files as $file) { if ($file["file_size"] <= $portal_max_file_size) { $file_item = $file_manager->getNewItem(); $file_item->setTempKey($file["file_id"]); $file_item->setPostFile($file); $file_item->save(); $file_id_array[] = $file_item->getFileID(); } else { $error['files_to_large'][] = array('name' => $file['name'], 'size' => $file["file_size"]); } } $material_item->setFileIDArray($file_id_array); $material_item->save(); // send e-mail with 'material created in your private room' back to sender $file = $_SERVER['PHP_SELF']; $file = str_replace('cron_email_upload', 'commsy', $file); $curl_text = 'http://' . $c_commsy_domain . $file . '?cid='; #$params['iid'] = $material_item->getItemID(); #$link_to_new_material = curl($private_room_id, 'material', 'detail', $params); //$link_to_new_material = '<a href="'.$curl_text.$private_room_id.'&mod=material&fct=detail&iid='.$material_item->getItemID().'">'.$material_item->getTitle().'</a>'; $result_body = $translator->getMessage('EMAIL_TO_COMMSY_RESULT_SUCCESS', $private_room_user->getFullName()) . "\n\n"; if (!empty($error['files_to_large'])) { $files_to_large = ''; foreach ($error['files_to_large'] as $file_to_large) { $files_to_large .= '- ' . $file_to_large['name'] . ' (' . round($file_to_large['size'] / (1024 * 1024), 2) . ' MB)' . "\n"; } $result_body .= $translator->getMessage('EMAIL_TO_COMMSY_RESULT_FILES_TO_LARGE', $portal_max_file_size / (1024 * 1024), $files_to_large) . "\n\n"; } $result_body .= $translator->getMessage('EMAIL_TO_COMMSY_RESULT_REGARDS'); $result_mail->set_subject('Upload2CommSy - erfolgreich'); $result_mail->set_message($result_body); } else { // send e-mail with 'password or subject not correct' back to sender $result_body = $translator->getMessage('EMAIL_TO_COMMSY_RESULT_FAILURE', $private_room_user->getFullName(), $translator->getMessage('EMAIL_TO_COMMSY_PASSWORD')); $result_mail->set_subject('Upload2CommSy - fehlgeschlagen'); $result_mail->set_message($result_body); } #$result_mail->setSendAsHTML(); $result_mail->send(); } } } // mark e-mail for deletion imap_delete($mbox, $msgno); }
/** * Start the email retrieval * * @param int $id email_setup.id */ function email_piping($id) { global $C_debug; # check for imap support: if (!is_callable('imap_open')) { $C_debug->error('core::email_piping', 'email_piping()', 'imap_open() - not supported'); return; } $db =& DB(); $sql = 'SELECT * FROM ' . AGILE_DB_PREFIX . 'setup_email WHERE site_id = ' . $db->qstr(DEFAULT_SITE) . ' AND id = ' . $db->qstr($id); $result = $db->Execute($sql); if ($result && $result->RecordCount()) { $this->cfg = $result->fields; $this->delete_action = $this->cfg['piping_action']; $type = $this->cfg['piping']; // imap/pop // get imap_open connection string $constr = $this->get_connection_string($type, $this->cfg['piping_host']); // attempt connection error_reporting(0); @($mbox = imap_open($constr, $this->cfg['piping_username'], $this->cfg['piping_password'])); // attempt alternate conneciton if (!$mbox) { $constr = $this->get_connection_string($type + 2, $this->cfg['piping_host']); @($mbox = imap_open($constr, $this->cfg['piping_username'], $this->cfg['piping_password'])); } // error log if (!$mbox) { $C_debug->error('core::email_piping', 'email_piping()', imap_last_error() . ' -- ' . $constr); return false; } // check for messages if (@($hdr = imap_check($mbox))) { $msgCount = $hdr->Nmsgs; if ($msgCount == 0) { return false; } } else { return false; // no messages } // get folder overview @($overview = imap_fetch_overview($mbox, "1:{$msgCount}", 0)); $size = sizeof($overview); // loop through messages for ($i = $size - 1; $i >= 0; $i--) { $val = $overview[$i]; $msg = $val->msgno; $this->attachments[$msg] = false; // formatting for from e-mail address $from = $val->from; $sender = $from = $val->from; $from = preg_replace("/\"/", "", $from); if (preg_match("/</", $from)) { $f = explode("<", $from); $sender = $f[0]; $from = $f[1]; $from = str_replace(">", "", $from); } // retrieve body $body = $this->get_part($mbox, $msg, "TEXT/PLAIN"); if (empty($body)) { $body = $this->get_part($mbox, $msg, "TEXT/HTML"); if (!empty($body)) { $body = str_replace("<br>", "\r\n", $body); } } // get attachements if ($this->get_attachments) { $struct = imap_fetchstructure($mbox, $msg); $contentParts = count($struct->parts); if ($contentParts >= 2) { for ($ii = 2; $ii <= $contentParts; $ii++) { $c = $ii - 2; $att[$c] = imap_bodystruct($mbox, $msg, $ii); } // download tmp file and add to attachemnt array for ($k = 0; $k < sizeof($att); $k++) { $tmp = $this->download_file($mbox, $msg, $k, $att[$k]->parameters[0]->value); } } } // Set the result array: $this->results[] = array('uniqueId' => $val->message_id, 'date' => $val->date, 'from' => trim($from), 'to' => $val->to, 'sender' => trim($sender), 'subject' => trim($val->subject), 'body' => trim($body), 'attach' => $this->attachments[$msg]); // mark for deletion or move if ($this->cfg['piping_action'] == 1) { if ($this->delete_action) { imap_delete($mbox, $msg); } else { if (($type == 2 || $type == 4) && !empty($this->move_mbox)) { imap_mail_move($mbox, $msg, $this->move_mbox); } } } } imap_close($mbox, CL_EXPUNGE); } }
protected function processDsn($messageId) { $result = array('email' => null, 'bounceType' => self::BOUNCE_HARD, 'action' => null, 'statusCode' => null, 'diagnosticCode' => null); $action = $statusCode = $diagnosticCode = null; // first part of DSN (Delivery Status Notification), human-readable explanation $dsnMessage = imap_fetchbody($this->_connection, $messageId, "1"); $dsnMessageStructure = imap_bodystruct($this->_connection, $messageId, "1"); if ($dsnMessageStructure->encoding == 4) { $dsnMessage = quoted_printable_decode($dsnMessage); } elseif ($dsnMessageStructure->encoding == 3) { $dsnMessage = base64_decode($dsnMessage); } // second part of DSN (Delivery Status Notification), delivery-status $dsnReport = imap_fetchbody($this->_connection, $messageId, "2"); if (preg_match("/Original-Recipient: rfc822;(.*)/i", $dsnReport, $matches)) { $emailArr = imap_rfc822_parse_adrlist($matches[1], 'default.domain.name'); if (isset($emailArr[0]->host) && $emailArr[0]->host != '.SYNTAX-ERROR.' && $emailArr[0]->host != 'default.domain.name') { $result['email'] = $emailArr[0]->mailbox . '@' . $emailArr[0]->host; } } else { if (preg_match("/Final-Recipient: rfc822;(.*)/i", $dsnReport, $matches)) { $emailArr = imap_rfc822_parse_adrlist($matches[1], 'default.domain.name'); if (isset($emailArr[0]->host) && $emailArr[0]->host != '.SYNTAX-ERROR.' && $emailArr[0]->host != 'default.domain.name') { $result['email'] = $emailArr[0]->mailbox . '@' . $emailArr[0]->host; } } } if (preg_match("/Action: (.+)/i", $dsnReport, $matches)) { $action = strtolower(trim($matches[1])); } if (preg_match("/Status: ([0-9\\.]+)/i", $dsnReport, $matches)) { $statusCode = $matches[1]; } // Could be multi-line , if the new line is beginning with SPACE or HTAB if (preg_match("/Diagnostic-Code:((?:[^\n]|\n[\t ])+)(?:\n[^\t ]|\$)/is", $dsnReport, $matches)) { $diagnosticCode = $matches[1]; } if (empty($result['email'])) { if (preg_match("/quota exceed.*<(\\S+@\\S+\\w)>/is", $dsnMessage, $matches)) { $result['email'] = $matches[1]; $result['bounceType'] = self::BOUNCE_SOFT; } } else { // "failed" / "delayed" / "delivered" / "relayed" / "expanded" if ($action == 'failed') { $rules = $this->getRules(); $foundMatch = false; foreach ($rules[self::DIAGNOSTIC_CODE_RULES] as $rule) { if (preg_match($rule['regex'], $diagnosticCode, $matches)) { $foundMatch = true; $result['bounceType'] = $rule['bounceType']; break; } } if (!$foundMatch) { foreach ($rules[self::DSN_MESSAGE_RULES] as $rule) { if (preg_match($rule['regex'], $dsnMessage, $matches)) { $foundMatch = true; $result['bounceType'] = $rule['bounceType']; break; } } } if (!$foundMatch) { foreach ($rules[self::COMMON_RULES] as $rule) { if (preg_match($rule['regex'], $dsnMessage, $matches)) { $foundMatch = true; $result['bounceType'] = $rule['bounceType']; break; } } } if (!$foundMatch) { $result['bounceType'] = self::BOUNCE_HARD; } } else { $result['bounceType'] = self::BOUNCE_SOFT; } } $result['action'] = $action; $result['statusCode'] = $statusCode; $result['diagnosticCode'] = $diagnosticCode; return $result; }
/** * Function to process each individual message * @param int $pos (message number) * @param string $type (DNS or BODY type) * @param string $totalFetched (total number of messages in mailbox) * @return boolean */ function processBounce($pos, $type, $totalFetched) { $header = imap_header($this->_mailbox_link, $pos); $subject = strip_tags($header->subject); $met = ini_get('max_execution_time'); if ($met < 6000 && $met != 0) { set_time_limit(6000); } imap_timeout(IMAP_READTIMEOUT, 6000); imap_timeout(IMAP_WRITETIMEOUT, 6000); if ($type == 'DSN') { // first part of DSN (Delivery Status Notification), human-readable explanation $dsn_msg = imap_fetchbody($this->_mailbox_link, $pos, "1"); $dsn_msg_structure = imap_bodystruct($this->_mailbox_link, $pos, "1"); if ($dsn_msg_structure->encoding == 4) { $dsn_msg = quoted_printable_decode($dsn_msg); } elseif ($dsn_msg_structure->encoding == 3) { $dsn_msg = base64_decode($dsn_msg); } // second part of DSN (Delivery Status Notification), delivery-status $dsn_report = imap_fetchbody($this->_mailbox_link, $pos, "2"); // process bounces by rules $result = bmhDSNRules($dsn_msg, $dsn_report, $this->debug_dsn_rule); } elseif ($type == 'BODY') { $structure = imap_fetchstructure($this->_mailbox_link, $pos); switch ($structure->type) { case 0: // Content-type = text // Content-type = text case 1: // Content-type = multipart $body = imap_fetchbody($this->_mailbox_link, $pos, "1"); // Detect encoding and decode - only base64 if (!empty($structure->parts[0]->encoding) && $structure->parts[0]->encoding == 4) { $body = quoted_printable_decode($body); } elseif (!empty($structure->parts[0]->encoding) && $structure->parts[0]->encoding == 3) { $body = base64_decode($body); } $result = bmhBodyRules($body, $structure, $this->debug_body_rule); break; case 2: // Content-type = message $body = imap_body($this->_mailbox_link, $pos); if ($structure->encoding == 4) { $body = quoted_printable_decode($body); } elseif ($structure->encoding == 3) { $body = base64_decode($body); } $body = substr($body, 0, 1000); $result = bmhBodyRules($body, $structure, $this->debug_body_rule); break; default: // unsupport Content-type $this->output('Msg #' . $pos . ' is unsupported Content-Type:' . $structure->type, VERBOSE_REPORT); return false; } } else { // internal error $this->error_msg = 'Internal Error: unknown type'; return false; } $email = $result['email']; $bounce_type = $result['bounce_type']; if ($this->moveHard && $result['remove'] == 1) { $remove = 'moved (hard)'; } elseif ($this->moveSoft && $result['remove'] == 1) { $remove = 'moved (soft)'; } elseif ($this->disable_delete) { $remove = 0; } else { $remove = $result['remove']; } $rule_no = $result['rule_no']; $rule_cat = $result['rule_cat']; $xheader = false; if ($rule_no == '0000') { // internal error return false; // code below will use the Callback function, but return no value if (trim($email) == '') { $email = $header->fromaddress; } $params = array($pos, $body, $bounce_type, $email, $subject, $xheader, $remove, $rule_no, $rule_cat, $totalFetched); call_user_func_array($this->action_function, $params); } else { // match rule, do bounce action if ($this->testmode) { $this->output('Match: ' . $rule_no . ':' . $rule_cat . '; ' . $bounce_type . '; ' . $email); return true; } else { $params = array($pos, $body, $bounce_type, $email, $subject, $xheader, $remove, $rule_no, $rule_cat, $totalFetched); return call_user_func_array($this->action_function, $params); } } }
public function indenx() { //echo "<pre>"; //print_r($_SERVER['HTTP_HOST']); //exit; $hostname = '{imap.gmail.com:993/imap/ssl}test'; $username = '******'; $password = '******'; $inbox = imap_open($hostname, $username, $password) or die('Cannot connect to Gmail: ' . imap_last_error()); /* grab emails */ $emails = imap_search($inbox, 'ALL'); $overview = imap_fetch_overview($inbox, 1, 0); print_r($overview); exit; /* if emails are returned, cycle through each... */ if ($emails) { /* begin output var */ $output = ''; $values = ''; /* put the newest emails on top */ rsort($emails); /* for every email... */ foreach ($emails as $email) { /* get information specific to this email */ $overview = imap_fetch_overview($inbox, $email, 0); $message = get_part($inbox, $email, "TEXT/HTML"); $attachments = ''; //$message = imap_fetchbody($inbox,$email,2); //imap_fetchstructure($inbox, $email); $struct = imap_fetchstructure($inbox, $email); $contentParts = count($struct->parts); if ($contentParts >= 2) { for ($i = 2; $i <= $contentParts; $i++) { $att[$i - 2] = imap_bodystruct($inbox, $email, $i); } for ($k = 0; $k < sizeof($att); $k++) { if ($att[$k]->parameters[0]->value == "us-ascii" || $att[$k]->parameters[0]->value == "US-ASCII") { if ($att[$k]->parameters[1]->value != "") { $strFileName = $att[$k]->parameters[1]->value; $strFileType = strrev(substr(strrev($strFileName), 0, 4)); $fileContent = imap_fetchbody($inbox, $email, 2); downloadFile($strFileType, $strFileName, $fileContent); $attachments .= $strFileName . ','; } } elseif ($att[$k]->parameters[0]->value != "iso-8859-1" && $att[$k]->parameters[0]->value != "ISO-8859-1") { $strFileName = $att[$k]->parameters[0]->value; $strFileType = strrev(substr(strrev($strFileName), 0, 4)); $fileContent = imap_fetchbody($inbox, $email, 2); //downloadFile($strFileType,$strFileName,$fileContent); $attachments .= $strFileName . ','; } } } } } // imap_msgno($inbox,$uid); //exit; $this->load->view('welcome_message'); }
/** * Imap synchronization method. * * @return array Errors list. */ public function syncImap() { if (!($url = Configuration::get('PS_SAV_IMAP_URL')) || !($port = Configuration::get('PS_SAV_IMAP_PORT')) || !($user = Configuration::get('PS_SAV_IMAP_USER')) || !($password = Configuration::get('PS_SAV_IMAP_PWD'))) { return array('hasError' => true, 'errors' => array('IMAP configuration is not correct')); } $conf = Configuration::getMultiple(array('PS_SAV_IMAP_OPT_POP3', 'PS_SAV_IMAP_OPT_NORSH', 'PS_SAV_IMAP_OPT_SSL', 'PS_SAV_IMAP_OPT_VALIDATE-CERT', 'PS_SAV_IMAP_OPT_NOVALIDATE-CERT', 'PS_SAV_IMAP_OPT_TLS', 'PS_SAV_IMAP_OPT_NOTLS')); $conf_str = ''; if ($conf['PS_SAV_IMAP_OPT_POP3']) { $conf_str .= '/pop3'; } if ($conf['PS_SAV_IMAP_OPT_NORSH']) { $conf_str .= '/norsh'; } if ($conf['PS_SAV_IMAP_OPT_SSL']) { $conf_str .= '/ssl'; } if ($conf['PS_SAV_IMAP_OPT_VALIDATE-CERT']) { $conf_str .= '/validate-cert'; } if ($conf['PS_SAV_IMAP_OPT_NOVALIDATE-CERT']) { $conf_str .= '/novalidate-cert'; } if ($conf['PS_SAV_IMAP_OPT_TLS']) { $conf_str .= '/tls'; } if ($conf['PS_SAV_IMAP_OPT_NOTLS']) { $conf_str .= '/notls'; } if (!function_exists('imap_open')) { return array('hasError' => true, 'errors' => array('imap is not installed on this server')); } $mbox = @imap_open('{' . $url . ':' . $port . $conf_str . '}', $user, $password); //checks if there is no error when connecting imap server $errors = imap_errors(); if (is_array($errors)) { $errors = array_unique($errors); } $str_errors = ''; $str_error_delete = ''; if (count($errors) && is_array($errors)) { $str_errors = ''; foreach ($errors as $error) { $str_errors .= $error . ', '; } $str_errors = rtrim(trim($str_errors), ','); } //checks if imap connexion is active if (!$mbox) { return array('hasError' => true, 'errors' => array('Cannot connect to the mailbox :<br />' . $str_errors)); } //Returns information about the current mailbox. Returns FALSE on failure. $check = imap_check($mbox); if (!$check) { return array('hasError' => true, 'errors' => array('Fail to get information about the current mailbox')); } if ($check->Nmsgs == 0) { return array('hasError' => true, 'errors' => array('NO message to sync')); } $result = imap_fetch_overview($mbox, "1:{$check->Nmsgs}", 0); $message_errors = array(); foreach ($result as $overview) { //check if message exist in database if (isset($overview->subject)) { $subject = $overview->subject; } else { $subject = ''; } //Creating an md5 to check if message has been allready processed $md5 = md5($overview->date . $overview->from . $subject . $overview->msgno); $exist = Db::getInstance()->getValue('SELECT `md5_header` FROM `' . _DB_PREFIX_ . 'customer_message_sync_imap` WHERE `md5_header` = \'' . pSQL($md5) . '\''); if ($exist) { if (Configuration::get('PS_SAV_IMAP_DELETE_MSG')) { if (!imap_delete($mbox, $overview->msgno)) { $str_error_delete = ', Fail to delete message'; } } } else { //check if subject has id_order preg_match('/\\#ct([0-9]*)/', $subject, $matches1); preg_match('/\\#tc([0-9-a-z-A-Z]*)/', $subject, $matches2); $match_found = false; if (isset($matches1[1]) && isset($matches2[1])) { $match_found = true; } $new_ct = Configuration::get('PS_SAV_IMAP_CREATE_THREADS') && !$match_found && strpos($subject, '[no_sync]') == false; $fetch_succeed = true; if ($match_found || $new_ct) { if ($new_ct) { // parse from attribute and fix it if needed $from_parsed = array(); if (!isset($overview->from) || !preg_match('/<(' . Tools::cleanNonUnicodeSupport('[a-z\\p{L}0-9!#$%&\'*+\\/=?^`{}|~_-]+[.a-z\\p{L}0-9!#$%&\'*+\\/=?^`{}|~_-]*@[a-z\\p{L}0-9]+[._a-z\\p{L}0-9-]*\\.[a-z0-9]+') . ')>/', $overview->from, $from_parsed) && !Validate::isEmail($overview->from)) { $message_errors[] = $this->trans('Cannot create message in a new thread.', array(), 'Admin.OrdersCustomers.Notification'); continue; } // fix email format: from "Mr Sanders <*****@*****.**>" to "*****@*****.**" $from = $overview->from; if (isset($from_parsed[1])) { $from = $from_parsed[1]; } // we want to assign unrecognized mails to the right contact category $contacts = Contact::getContacts($this->context->language->id); if (!$contacts) { continue; } foreach ($contacts as $contact) { if (isset($overview->to) && strpos($overview->to, $contact['email']) !== false) { $id_contact = $contact['id_contact']; } } if (!isset($id_contact)) { // if not use the default contact category $id_contact = $contacts[0]['id_contact']; } $customer = new Customer(); $client = $customer->getByEmail($from); //check if we already have a customer with this email $ct = new CustomerThread(); if (isset($client->id)) { //if mail is owned by a customer assign to him $ct->id_customer = $client->id; } $ct->email = $from; $ct->id_contact = $id_contact; $ct->id_lang = (int) Configuration::get('PS_LANG_DEFAULT'); $ct->id_shop = $this->context->shop->id; //new customer threads for unrecognized mails are not shown without shop id $ct->status = 'open'; $ct->token = Tools::passwdGen(12); $ct->add(); } else { $ct = new CustomerThread((int) $matches1[1]); } //check if order exist in database if (Validate::isLoadedObject($ct) && (isset($matches2[1]) && $ct->token == $matches2[1] || $new_ct)) { $structure = imap_bodystruct($mbox, $overview->msgno, '1'); if ($structure->type == 0) { $message = imap_fetchbody($mbox, $overview->msgno, '1'); } elseif ($structure->type == 1) { $structure = imap_bodystruct($mbox, $overview->msgno, '1.1'); $message = imap_fetchbody($mbox, $overview->msgno, '1.1'); } else { continue; } switch ($structure->encoding) { case 3: $message = imap_base64($message); break; case 4: $message = imap_qprint($message); break; } $message = iconv($this->getEncoding($structure), 'utf-8', $message); $message = nl2br($message); if (!$message || strlen($message) == 0) { $message_errors[] = $this->trans('The message body is empty, cannot import it.', array(), 'Admin.OrdersCustomers.Notification'); $fetch_succeed = false; continue; } $cm = new CustomerMessage(); $cm->id_customer_thread = $ct->id; if (empty($message) || !Validate::isCleanHtml($message)) { $str_errors .= Tools::displayError(sprintf('Invalid Message Content for subject: %1s', $subject)); } else { try { $cm->message = $message; $cm->add(); } catch (PrestaShopException $pse) { $message_errors[] = $this->trans('The message content is not valid, cannot import it.', array(), 'Admin.OrdersCustomers.Notification'); $fetch_succeed = false; continue; } } } } if ($fetch_succeed) { Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'customer_message_sync_imap` (`md5_header`) VALUES (\'' . pSQL($md5) . '\')'); } } } imap_expunge($mbox); imap_close($mbox); if (sizeof($message_errors) > 0) { if (($more_error = $str_errors . $str_error_delete) && strlen($more_error) > 0) { $message_errors = array_merge(array($more_error), $message_errors); } return array('hasError' => true, 'errors' => $message_errors); } if ($str_errors . $str_error_delete) { return array('hasError' => true, 'errors' => array($str_errors . $str_error_delete)); } else { return array('hasError' => false, 'errors' => ''); } }
private function decodePart($part) { $bodyStructure = imap_bodystruct($this->imap_stream, $this->message_index, $part); $att_data = imap_fetchbody($this->imap_stream, $this->message_index, $part); switch ($bodyStructure->encoding) { case '1': //utf7 //php lies, this is 0 $filedata = @imap_utf7_decode($att_data); break; // case '1': //utf8 //php lies, this is utf7 // $filedata = imap_utf8($att_data); // break; // case '1': //utf8 //php lies, this is utf7 // $filedata = imap_utf8($att_data); // break; case '3': //base64 $filedata = imap_base64($att_data); break; case '4': //quoted printable $filedata = imap_qprint($att_data); break; default: $filedata = $att_data; } return $filedata; }
/** * Function to process each individual message. * * @param int $pos message number * @param string $type DNS or BODY type * @param string $totalFetched total number of messages in mailbox * * @return boolean */ public function processBounce($pos, $type, $totalFetched) { $header = imap_header($this->mailboxLink, $pos); $subject = isset($header->subject) ? strip_tags($header->subject) : '[NO SUBJECT]'; $body = ''; $headerFull = imap_fetchheader($this->mailboxLink, $pos); $bodyFull = imap_body($this->mailboxLink, $pos); if ($type == 'DSN') { // first part of DSN (Delivery Status Notification), human-readable explanation $dsnMsg = imap_fetchbody($this->mailboxLink, $pos, '1'); $dsnMsgStructure = imap_bodystruct($this->mailboxLink, $pos, '1'); if ($dsnMsgStructure->encoding == 4) { $dsnMsg = quoted_printable_decode($dsnMsg); } elseif ($dsnMsgStructure->encoding == 3) { $dsnMsg = base64_decode($dsnMsg); } // second part of DSN (Delivery Status Notification), delivery-status $dsnReport = imap_fetchbody($this->mailboxLink, $pos, '2'); // process bounces by rules $result = bmhDSNRules($dsnMsg, $dsnReport, $this->debugDsnRule); $result = is_callable($this->customDSNRulesCallback) ? call_user_func($this->customDSNRulesCallback, $result, $dsnMsg, $dsnReport, $this->debugDsnRule) : $result; } elseif ($type == 'BODY') { /** @noinspection PhpUsageOfSilenceOperatorInspection */ $structure = @imap_fetchstructure($this->mailboxLink, $pos); if (!is_object($structure)) { return false; } switch ($structure->type) { case 0: // Content-type = text $body = imap_fetchbody($this->mailboxLink, $pos, '1'); $result = bmhBodyRules($body, $structure, $this->debugBodyRule); $result = is_callable($this->customBodyRulesCallback) ? call_user_func($this->customBodyRulesCallback, $result, $body, $structure, $this->debugBodyRule) : $result; break; case 1: // Content-type = multipart $body = imap_fetchbody($this->mailboxLink, $pos, '1'); // Detect encoding and decode - only base64 if ($structure->parts[0]->encoding == 4) { $body = quoted_printable_decode($body); } elseif ($structure->parts[0]->encoding == 3) { $body = base64_decode($body); } $result = bmhBodyRules($body, $structure, $this->debugBodyRule); $result = is_callable($this->customBodyRulesCallback) ? call_user_func($this->customBodyRulesCallback, $result, $body, $structure, $this->debugBodyRule) : $result; break; case 2: // Content-type = message $body = imap_body($this->mailboxLink, $pos); if ($structure->encoding == 4) { $body = quoted_printable_decode($body); } elseif ($structure->encoding == 3) { $body = base64_decode($body); } $body = substr($body, 0, 1000); $result = bmhBodyRules($body, $structure, $this->debugBodyRule); $result = is_callable($this->customBodyRulesCallback) ? call_user_func($this->customBodyRulesCallback, $result, $body, $structure, $this->debugBodyRule) : $result; break; default: // unsupport Content-type $this->output('Msg #' . $pos . ' is unsupported Content-Type:' . $structure->type, self::VERBOSE_REPORT); return false; } } else { // internal error $this->errorMessage = 'Internal Error: unknown type'; return false; } $email = $result['email']; $bounceType = $result['bounce_type']; // workaround: I think there is a error in one of the reg-ex in "phpmailer-bmh_rules.php". if ($email && strpos($email, 'TO:<')) { $email = str_replace('TO:<', '', $email); } if ($this->moveHard && $result['remove'] == 1) { $remove = 'moved (hard)'; } elseif ($this->moveSoft && $result['remove'] == 1) { $remove = 'moved (soft)'; } elseif ($this->disableDelete) { $remove = 0; } else { $remove = $result['remove']; } $ruleNumber = $result['rule_no']; $ruleCategory = $result['rule_cat']; $status_code = $result['status_code']; $action = $result['action']; $diagnostic_code = $result['diagnostic_code']; $xheader = false; if ($ruleNumber === '0000') { // unrecognized if (trim($email) == '' && property_exists($header, 'fromaddress') === true) { $email = $header->fromaddress; } if ($this->testMode) { $this->output('Match: ' . $ruleNumber . ':' . $ruleCategory . '; ' . $bounceType . '; ' . $email); } else { // code below will use the Callback function, but return no value $params = array($pos, $bounceType, $email, $subject, $header, $remove, $ruleNumber, $ruleCategory, $totalFetched, $body, $headerFull, $bodyFull, $status_code, $action, $diagnostic_code); call_user_func_array($this->actionFunction, $params); } } else { // match rule, do bounce action if ($this->testMode) { $this->output('Match: ' . $ruleNumber . ':' . $ruleCategory . '; ' . $bounceType . '; ' . $email); return true; } else { $params = array($pos, $bounceType, $email, $subject, $xheader, $remove, $ruleNumber, $ruleCategory, $totalFetched, $body, $headerFull, $bodyFull, $status_code, $action, $diagnostic_code); return call_user_func_array($this->actionFunction, $params); } } return false; }
/** * Function to process each individual message * * @param int $pos message number * @param string $type DNS or BODY type * @param string $totalFetched total number of messages in mailbox * * @return boolean */ public function processBounce($pos, $type, $totalFetched) { $header = imap_header($this->mailboxLink, $pos); $subject = strip_tags($header->subject); $body = ''; if ($type == 'DSN') { // first part of DSN (Delivery Status Notification), human-readable explanation $dsnMsg = imap_fetchbody($this->mailboxLink, $pos, "1"); $dsnMsgStructure = imap_bodystruct($this->mailboxLink, $pos, "1"); if ($dsnMsgStructure->encoding == 4) { $dsnMsg = quoted_printable_decode($dsnMsg); } elseif ($dsnMsgStructure->encoding == 3) { $dsnMsg = base64_decode($dsnMsg); } // second part of DSN (Delivery Status Notification), delivery-status $dsnReport = imap_fetchbody($this->mailboxLink, $pos, "2"); // process bounces by rules $result = bmhDSNRules($dsnMsg, $dsnReport, $this->debugDsnRule); } elseif ($type == 'BODY') { $structure = imap_fetchstructure($this->mailboxLink, $pos); switch ($structure->type) { case 0: // Content-type = text $body = imap_fetchbody($this->mailboxLink, $pos, "1"); $result = bmhBodyRules($body, $structure, $this->debugBodyRule); break; case 1: // Content-type = multipart $body = imap_fetchbody($this->mailboxLink, $pos, "1"); // Detect encoding and decode - only base64 if ($structure->parts[0]->encoding == 4) { $body = quoted_printable_decode($body); } elseif ($structure->parts[0]->encoding == 3) { $body = base64_decode($body); } $result = bmhBodyRules($body, $structure, $this->debugBodyRule); break; case 2: // Content-type = message $body = imap_body($this->mailboxLink, $pos); if ($structure->encoding == 4) { $body = quoted_printable_decode($body); } elseif ($structure->encoding == 3) { $body = base64_decode($body); } $body = substr($body, 0, 1000); $result = bmhBodyRules($body, $structure, $this->debugBodyRule); break; default: // unsupport Content-type $this->output('Msg #' . $pos . ' is unsupported Content-Type:' . $structure->type, self::VERBOSE_REPORT); return false; } } else { // internal error $this->errorMessage = 'Internal Error: unknown type'; return false; } $email = $result['email']; $bounceType = $result['bounce_type']; if ($this->moveHard && $result['remove'] == 1) { $remove = 'moved (hard)'; } elseif ($this->moveSoft && $result['remove'] == 1) { $remove = 'moved (soft)'; } elseif ($this->disableDelete) { $remove = 0; } else { $remove = $result['remove']; } $ruleNumber = $result['rule_no']; $ruleCategory = $result['rule_cat']; $xheader = false; if ($ruleNumber === '0000') { // unrecognized if (trim($email) == '') { $email = $header->fromaddress; } if ($this->testMode) { $this->output('Match: ' . $ruleNumber . ':' . $ruleCategory . '; ' . $bounceType . '; ' . $email); } else { // code below will use the Callback function, but return no value $params = array($pos, $bounceType, $email, $subject, $header, $remove, $ruleNumber, $ruleCategory, $totalFetched, $body); call_user_func_array($this->actionFunction, $params); } } else { // match rule, do bounce action if ($this->testMode) { $this->output('Match: ' . $ruleNumber . ':' . $ruleCategory . '; ' . $bounceType . '; ' . $email); return true; } else { $params = array($pos, $bounceType, $email, $subject, $xheader, $remove, $ruleNumber, $ruleCategory, $totalFetched, $body); return call_user_func_array($this->actionFunction, $params); } } }
private function handleBodyTextPart($connection, $msg, $part, $basePartNr, $partNr, $encoding) { //first check if this message part is not a part of the body //but an attachment with the encoding text plain $bodyStruct = imap_bodystruct($connection, $msg, $basePartNr . $partNr); if ($bodyStruct->ifparameters) { foreach ($bodyStruct->parameters as $p) { $params[strtolower($p->attribute)] = mb_decode_mimeheader($p->value); } } if ($bodyStruct->ifdparameters) { foreach ($bodyStruct->dparameters as $p) { $params[strtolower($p->attribute)] = mb_decode_mimeheader($p->value); } } if (array_key_exists("filename", $params) && array_key_exists("attachments", $this->requiredProperties)) { $fileName = $params['filename']; if (!mb_check_encoding($fileName, "UTF-8")) { $fileName = utf8_encode($fileName); } $result = $this->handleAttachments($bodyStruct, $connection, $msg, $basePartNr . $partNr, $encoding); if ($result != "true") { $this->messageContainsErrors = true; $this->createErrorMessage($connection, $msg, $result); } } else { if ($part->ifsubtype) { if (strtoupper($part->subtype) == "X-VCARD") { if (!array_key_exists("attachments", $this->requiredProperties)) { return; } $result = $this->serialiseVCard($this->decodeBodyPart(imap_fetchbody($connection, $msg, $basePartNr . $partNr), $encoding)); if ($result != "true") { $this->createErrorMessage($connection, $msg, $result); $this->messageContainsErrors = true; } } else { if (strtoupper($part->subtype) == "CALENDAR") { if (!array_key_exists("attachments", $this->requiredProperties)) { return; } $content = $this->decodeBodyPart(imap_fetchbody($connection, $msg, $basePartNr . $partNr), $encoding); $result = $this->serializeICal($content); if ($result != "true") { $this->createErrorMessage($connection, $msg, $result); $this->messageContainsErrors = true; } } else { if (array_key_exists("body", $this->requiredProperties) && strtoupper($part->subtype) != "HTML") { $body = htmlspecialchars($this->decodeBodyPart(imap_fetchbody($connection, $msg, $basePartNr . $partNr), $encoding)); if (!mb_check_encoding($body, "UTF-8")) { $body = utf8_encode($body); } $body = nl2br($body); $body = $this->replaceSpecialWikiCharacters($body); $this->body .= $body; } } } } else { if (array_key_exists("body", $this->requiredProperties)) { //text message without subtype $body = "<pre>" . htmlspecialchars($this->decodeBodyPart(imap_fetchbody($connection, $msg, $basePartNr . $partNr), $encoding)) . "</pre>"; if (!mb_check_encoding($body, "UTF-8")) { $body = utf8_encode($body); } $body = nl2br($body); $body = $this->replaceSpecialWikiCharacters($body); $this->body .= $body; } } } }