/** * Parse the Message into parts * @return void * @private */ private function parse() { $structure = mailparse_msg_get_structure($this->resource); $this->parts = array(); foreach ($structure as $part_id) { $part = mailparse_msg_get_part($this->resource, $part_id); $this->parts[$part_id] = mailparse_msg_get_part_data($part); } }
/** * Parse the Message into parts * * @return void */ protected function parse() { $structure = mailparse_msg_get_structure($this->resource); $this->parts = []; foreach ($structure as $part_id) { $part = mailparse_msg_get_part($this->resource, $part_id); $this->parts[$part_id] = mailparse_msg_get_part_data($part); } }
/** * Enter description here... * * @param object $mime * @return CerberusParserMessage */ public static function parseMime($mime, $full_filename) { $struct = mailparse_msg_get_structure($mime); $msginfo = mailparse_msg_get_part_data($mime); $message = new CerberusParserMessage(); @($message->encoding = $msginfo['content-charset']); @($message->body_encoding = $message->encoding); // default // Decode headers @($message->headers = $msginfo['headers']); if (is_array($message->headers)) { foreach ($message->headers as $header_name => $header_val) { if (is_array($header_val)) { foreach ($header_val as $idx => $val) { $message->headers[$header_name][$idx] = self::fixQuotePrintableString($val); } } else { $message->headers[$header_name] = self::fixQuotePrintableString($header_val); } } } $settings = DevblocksPlatform::getPluginSettingsService(); $is_attachments_enabled = $settings->get('cerberusweb.core', CerberusSettings::ATTACHMENTS_ENABLED, 1); $attachments_max_size = $settings->get('cerberusweb.core', CerberusSettings::ATTACHMENTS_MAX_SIZE, 10); foreach ($struct as $st) { // echo "PART $st...<br>\r\n"; $section = mailparse_msg_get_part($mime, $st); $info = mailparse_msg_get_part_data($section); // handle parts that shouldn't have a content-name, don't handle twice $handled = 0; if (empty($info['content-name'])) { if ($info['content-type'] == 'text/plain') { $text = mailparse_msg_extract_part_file($section, $full_filename, NULL); if (isset($info['content-charset']) && !empty($info['content-charset'])) { $message->body_encoding = $info['content-charset']; if (@mb_check_encoding($text, $info['content-charset'])) { $text = mb_convert_encoding($text, LANG_CHARSET_CODE, $info['content-charset']); } else { $text = mb_convert_encoding($text, LANG_CHARSET_CODE); } } @($message->body .= $text); unset($text); $handled = 1; } elseif ($info['content-type'] == 'text/html') { @($text = mailparse_msg_extract_part_file($section, $full_filename, NULL)); if (isset($info['content-charset']) && !empty($info['content-charset'])) { if (@mb_check_encoding($text, $info['content-charset'])) { $text = mb_convert_encoding($text, LANG_CHARSET_CODE, $info['content-charset']); } else { $text = mb_convert_encoding($text, LANG_CHARSET_CODE); } } $message->htmlbody .= $text; unset($text); // Add the html part as an attachment // [TODO] Make attaching the HTML part an optional config option (off by default) $tmpname = ParserFile::makeTempFilename(); $html_attach = new ParserFile(); $html_attach->setTempFile($tmpname, 'text/html'); @file_put_contents($tmpname, $message->htmlbody); $html_attach->file_size = filesize($tmpname); $message->files["original_message.html"] = $html_attach; unset($html_attach); $handled = 1; } elseif ($info['content-type'] == 'message/rfc822') { @($message_content = mailparse_msg_extract_part_file($section, $full_filename, NULL)); $message_counter = empty($message_counter) ? 1 : $message_counter + 1; $tmpname = ParserFile::makeTempFilename(); $html_attach = new ParserFile(); $html_attach->setTempFile($tmpname, 'message/rfc822'); @file_put_contents($tmpname, $message_content); $html_attach->file_size = filesize($tmpname); $message->files['inline' . $message_counter . '.msg'] = $html_attach; unset($html_attach); $handled = 1; } } // whether or not it has a content-name, we need to add it as an attachment (if not already handled) if ($handled == 0) { if (false === strpos(strtolower($info['content-type']), 'multipart')) { if (!$is_attachments_enabled) { break; // skip attachment } $attach = new ParseCronFileBuffer($section, $info, $full_filename); // [TODO] This could be more efficient by not even saving in the first place above: // Make sure our attachment is under the max preferred size if (filesize($attach->tmpname) > $attachments_max_size * 1024000) { @unlink($attach->tmpname); break; } // if un-named, call it "unnamed message part" if (!isset($info['content-name']) || isset($info['content-name']) && empty($info['content-name'])) { // or blank $info['content-name'] = 'unnamed_message_part'; } // filenames can be quoted-printable strings, too... $info['content-name'] = self::fixQuotePrintableString($info['content-name']); // content-name is not necessarily unique... if (isset($message->files[$info['content-name']])) { $j = 1; while (isset($message->files[$info['content-name'] . '(' . $j . ')'])) { $j++; } $info['content-name'] = $info['content-name'] . '(' . $j . ')'; } $message->files[$info['content-name']] = $attach; } } } // generate the plaintext part (if necessary) if (empty($message->body) && !empty($message->htmlbody)) { $message->body = CerberusApplication::stripHTML($message->htmlbody); } return $message; }
if (!$userId) { $errors[] = "You e-mailed <{$recipient}> but \"{$mailAuthToken}\" is not a valid authentication token."; sendReport($sender, $errors, $notices); unlink($tmpFile); exit; } // Iterate structure $body = ""; $attachments = array(); foreach ($structure as $structurePart) { $partFile = "{$tmpFile}-{$structurePart}"; $section = mailparse_msg_get_part($mp, $structurePart); $info = mailparse_msg_get_part_data($section); if (!in_array($info['content-type'], array('multipart/mixed', 'multipart/alternative'))) { // Get contents $part = mailparse_msg_get_part($mp, $structurePart); // Use NULL as callback to return as string and not to STDOUT. $contents = mailparse_msg_extract_part_file($part, $tmpFile, NULL); if (isset($info['disposition-filename'])) { // Attachment, store $name = iconv_mime_decode($info['disposition-filename']); $id = Storage::save($name, $contents); $attachments[] = $id; } else { if (!$body && $info['content-type'] == 'text/plain') { // Body part $body = trim(preg_replace('/-- [\\r\\n]+.*/s', '', $contents)); } } } }
$match_array["D-Link Camera Alert: Camera-Sam - PIR Sensor Triggered"] = "https://graph.api.smartthings.com/api/smartapps/installations/INSTANCE/%ACTION%?access_token=TOKEN"; $match_array["D-Link Camera Alert: Camera-Loft - PIR Sensor Triggered"] = "https://graph.api.smartthings.com/api/smartapps/installations/INSTANCE/%ACTION%?access_token=TOKEN"; // read email $fd = fopen("php://stdin", "r"); $email = ""; while (!feof($fd)) { $line = fread($fd, 1024); $email .= $line; } fclose($fd); $email_file = "/tmp/email_" . rand(); file_put_contents($email_file, $email); $mime = mailparse_msg_parse_file($email_file); $struct = mailparse_msg_get_structure($mime); foreach ($struct as $st) { $section = mailparse_msg_get_part($mime, $st); $info = mailparse_msg_get_part_data($section); $subject = $info[headers][subject]; $curl_string = $match_array[$subject]; // trigger event active $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, str_replace("%ACTION%", "active", $curl_string)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0); curl_exec($ch); curl_close($ch); sleep(15); // trigger event inactive $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, str_replace("%ACTION%", "inactive", $curl_string)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0); curl_exec($ch);
/** * Send an email. * * This is a re-implementation of PHP's mail() function using App Engine * mail API. The function relies on mailparse extension to parse emails. * * @param string $to Receiver, or receivers of the mail. * @param string $subject Subject of the email to be sent. * @param string $message Message to be sent. * @param string $additional_headers optional * String to be inserted at the end of the email header. * @param string $additional_parameters optional * Additional flags to be passed to the mail program. This arugment is * added only to match the signature of PHP's mail() function. The value is * always ignored. * @return bool * TRUE if the message is sent successfully, otherwise return FALSE. * * @see http://php.net/mail */ public static function sendMail($to, $subject, $message, $additional_headers = null, $additional_parameters = null) { $raw_mail = "To: {$to}\r\nSubject: {$subject}\r\n"; if ($additional_headers != null) { $raw_mail .= trim($additional_headers); } $raw_mail .= "\r\n\r\n{$message}"; $mime = mailparse_msg_create(); mailparse_msg_parse($mime, $raw_mail); $root_part = mailparse_msg_get_part_data($mime); // Set sender address based on the following order // 1. "From" header in $additional_headers // 2. "sendmail_from" ini setting // 3. Default address "mailer@<app-id>.appspotmail.com $from = ini_get('sendmail_from'); if (isset($root_part['headers']['from'])) { $from = $root_part['headers']['from']; } if ($from === false || $from == "") { $from = sprintf(self::DEFAULT_SENDER_ADDRESS_FORMAT, AppIdentityService::getApplicationId()); syslog(LOG_WARNING, "mail(): Unable to determine sender's email address from the " . "'sendmail_from' directive in php.ini or from the 'From' " . "header. Falling back to the default {$from}."); } $email = new Message(); try { $email->setSender($from); $email->addTo($root_part['headers']['to']); if (isset($root_part['headers']['cc'])) { $email->AddCc($root_part['headers']['cc']); } if (isset($root_part['headers']['bcc'])) { $email->AddBcc($root_part['headers']['bcc']); } $email->setSubject($root_part['headers']['subject']); $parts = mailparse_msg_get_structure($mime); if (count($parts) > 1) { foreach ($parts as $part_id) { $part = mailparse_msg_get_part($mime, $part_id); self::parseMimePart($part, $raw_mail, $email); } } else { if ($root_part['content-type'] == 'text/plain') { $email->setTextBody($message); } else { if ($root_part['content-type'] == 'text/html') { $email->setHtmlBody($message); } } } $email->send(); } catch (\Exception $e) { trigger_error('mail(): ' . $e->getMessage(), E_USER_WARNING); return false; } return true; }
echo "\nExtract whole part to output\n"; mailparse_msg_extract_whole_part_file($mime, $fp); echo "\nExtract part from string to output\n"; mailparse_msg_extract_part($mime, $text); fclose($fpdest); fclose($fp); $output = ob_get_contents(); ob_end_clean(); VS($output, "Extract to output\n" . "hello, this is some text hello.\n" . "blah blah blah.\n" . "Extract and return as string\n" . "-->\n" . "hello, this is some text hello.\n" . "blah blah blah.\n" . "\n" . "Extract to open file\n" . "\n" . "rewinding\n" . "hello, this is some text hello.\n" . "blah blah blah.\n" . "\n" . "Extract via user function\n" . "hello, this is some text hello.\n" . "blah blah blah.\n" . "\n" . "Extract whole part to output\n" . "To: fred@bloggs.com\n" . "Mime-Version: 1.0\n" . "Content-Type: text/plain\n" . "Subject: A simple MIME message\n" . "\n" . "hello, this is some text hello.\n" . "blah blah blah.\n" . "\n" . "Extract part from string to output\n" . "hello, this is some text hello.\n" . "blah blah blah.\n"); ////////////////////////////////////////////////////////////////////// $msg = "Received: from mail pickup service by hotmail.com with Microsoft\n" . "SMTPSVC;\n" . "Sat, 18 Feb 2006 22:58:14 -0800\n" . "Received: from 66.178.40.49 by BAY116-DAV8.phx.gbl with DAV;\n" . "Sun, 19 Feb 2006 06:58:13 +0000\n" . "\n" . "test"; $mail = mailparse_msg_create(); mailparse_msg_parse($mail, $msg); $arr = mailparse_msg_get_structure($mail); foreach ($arr as $first => $second) { $section = mailparse_msg_get_part($mail, $second); $info = mailparse_msg_get_part_data($section); $received = array("from mail pickup service by hotmail.com with Microsoft", "from 66.178.40.49 by BAY116-DAV8.phx.gbl with DAV;"); VS($info, array("headers" => array("received" => $received), "starting-pos" => 0, "starting-pos-body" => 200, "ending-pos" => 200, "ending-pos-body" => 200, "line-count" => 6, "body-line-count" => 0, "charset" => "us-ascii", "transfer-encoding" => "8bit", "content-type" => "text/plain", "content-base" => "/")); } ////////////////////////////////////////////////////////////////////// $addresses = array("\":sysmail\"@ Some-Group. Some-Org, Muhammed." . "(I am the greatest) Ali @(the)Vegas.WBA", "\"strange\":\":sysmail\"@ Some-Group. Some-Org, Muhammed." . "(I am the greatest) Ali @(the)Vegas.WBA;"); ob_start(); foreach ($addresses as $first => $second) { $parsed = mailparse_rfc822_parse_addresses($second); foreach ($parsed as $pfirst => $psecond) { $pair = $psecond; echo $pair['display']; echo "\n"; echo $pair['address']; echo "\n";
#!/usr/local/bin/php <?php ob_start('EmailOutput'); function EmailOutput($str) { if (strlen(trim($str)) > 0) { mail('*****@*****.**', 'Output from incomingmail.php', $str, 'From: TwitApps <*****@*****.**>', '*****@*****.**'); } } $data = file_get_contents('php://stdin'); $msg = mailparse_msg_create(); if (!mailparse_msg_parse($msg, $data)) { mail('*****@*****.**', 'TwitApps incoming mail: Parse failed', $data, 'From: TwitApps <*****@*****.**>', '*****@*****.**'); } else { $message = mailparse_msg_get_part($msg, 1); $info = mailparse_msg_get_part_data($message); if (!$message or !$info) { mail('*****@*****.**', 'TwitApps incoming mail: Failed to get message or info', $data, 'From: TwitApps <*****@*****.**>', '*****@*****.**'); } else { ob_start(); mailparse_msg_extract_part($message, $data); $body = ob_get_clean(); $body = urldecode($body); $body = iconv($info['charset'], 'UTF-8', $body); $body = html_entity_decode($body, ENT_NOQUOTES, 'UTF-8'); //mail('*****@*****.**', $info['headers']['subject'], $body."\n\n========================================\n\n".$data, 'From: TwitApps <*****@*****.**>', '*****@*****.**'); switch (@$info['headers']['x-twitterrecipientscreenname']) { case 'ta_follows': require dirname(__FILE__) . '/../follows/cli/incoming_mail.php'; break; case 'ta_replies':
/** * @param string $section * * @return resource */ public function getPart(string $section) { return mailparse_msg_get_part($this->resource, $section); }
/* print a choice of sections */ foreach ($struct as $st) { echo "<tr>\n"; echo "<td><a href=\"{$PHP_SELF}?showpart={$st}\">{$st}</a></td>\n"; /* get a handle on the message resource for a subsection */ $section = mailparse_msg_get_part($mime, $st); /* get content-type, encoding and header information for that section */ $info = mailparse_msg_get_part_data($section); print_r($info); echo "\n"; echo "<td>" . $info["content-type"] . "</td>\n"; echo "<td>" . $info["content-disposition"] . "</td>\n"; echo "<td>" . $info["disposition-filename"] . "</td>\n"; echo "<td>" . $info["charset"] . "</td>\n"; echo "</tr>"; } echo "</table>"; /* if we were called to display a part, do so now */ if ($showpart) { /* get a handle on the message resource for the desired part */ $sec = mailparse_msg_get_part($mime, $showpart); echo "<table border=1><tr><th>Section {$showpart}</th></tr><tr><td>"; ob_start(); /* extract the part from the message file and dump it to the output buffer * */ mailparse_msg_extract_part_file($sec, $filename); $contents = ob_get_contents(); ob_end_clean(); /* quote the message for safe display in a browser */ echo nl2br(htmlentities($contents)) . "</td></tr></table>"; }