Difference between revisions of "Display Alert Email Notification"

From LinuxMCE
Jump to: navigation, search
(Undo revision 17684 by Freymann (Talk))
 
(4 intermediate revisions by 4 users not shown)
Line 1: Line 1:
 +
[[Category: automation]]
 +
[[Category:Configuration]]
 +
 +
 
The concept around this article is pretty simple:
 
The concept around this article is pretty simple:
  
*Make the core monitor as many pop3 email accounts as you want for new messages
+
*Make the core monitor POP3 email accounts for new messages  (as many accounts as you want)
 
*Pop up a Display Alert window indicating who the new message is from and the subject
 
*Pop up a Display Alert window indicating who the new message is from and the subject
 
*Track messages we've dealt with so we aren't constantly reminded about the same message over and over
 
*Track messages we've dealt with so we aren't constantly reminded about the same message over and over

Latest revision as of 23:24, 19 October 2012


The concept around this article is pretty simple:

  • Make the core monitor POP3 email accounts for new messages (as many accounts as you want)
  • Pop up a Display Alert window indicating who the new message is from and the subject
  • Track messages we've dealt with so we aren't constantly reminded about the same message over and over
  • Provide an 'ignore message with this text in the subject line' function

This allows me to use the LMCE boxes in the house and keep an eye in incoming email messages. If I see a message that I think I may need to deal with I can then pause whatever is going on, go to my email, and then come back.

You need to get the pop3.class.inc file from this location:

http://www.phpclasses.org/browse/package/1120.html

Just scroll to the bottom where you can click on DOWNLOAD and save it. There's also a version available for PHP5.

For those that some how miss the fact you can click on the class and download it without being logged in (you probably didn't scroll all the way to the bottom!) I've put a copy of pop3.class.inc online here:

http://ww2.interpool.ca/files/pop3.class.inc

You can also get a copy of my php script here:

http://ww2.interpool.ca/files/chkmail.php

as the formatting on this page may not work well for the source code below.

Now you'll need to copy and paste this code into a file (I called it chkmail.php):


<?php

// A little php script to check for new mail messages and sent a display_alert
// command to alert LinuxMCE users of new email messages
// Put this script and the pop3.class.inc somewhere. Data files will be created
// in this directory to store data about incoming messages.
// To run it:  php chkmail.php
// and press Ctrl-C to stop. Or make it a background job:
// php chkmail.php &
//
// -------------------------------------------------------------
// Add your mail account info to the $mail_accounts array
// Separate your different accounts with opening/closing quotes
// Separeate your account info with a semi-colon (;)
// $mail_accounts = array("pop3.servername;pop.username;pop3.password")
// Add as many accounts as you like
// $mail_accounts = array("pop3.servername;pop.username;pop3.password","pop3.servername2;pop.username2;pop3.password2")
//

$mail_accounts = array("pop.server1;username1;password1","pop.server2;username2;password2");

$ignore_subjects = array("Cron");

// # of seconds between mail checks. 300 = 5 mins.
$waitfor = 300;

//
// You shouldn't have to edit anything below
// -------------------------------------------------------------

require_once('pop3.class.inc');

$pop3 = new POP3;

while (1) {

   foreach ($mail_accounts as $account) {

	list($mailserver,$username,$password) = explode(";", $account);

	// Read in data file for this account
	$file_name = $mailserver . "-" . $username . ".cfg";
	$ids = read_file($file_name);
	if ($ids == false) {
		// That's ok, no previous data
		$ids = array();
		$orig_count = 0;
	} else {
		$orig_count = count($ids);
		for ($i = 0; $i < $orig_count; $i++) {
			// Want to strip carraige returns and line feeds so our array
			// comparisons later match correctly
			$ids[$i] = ereg_replace("\n\r|\r\n|\n", "", $ids[$i]);
		}
	}

	// Connect to mail server
	$do = $pop3->connect($mailserver);
	if ($do == false) {
		echo $pop3->error;
		continue;
	}

	// Login to your inbox
	$do = $pop3->login($username, $password);
	if ($do == false) {
    	 	echo $pop3->error;
		continue;
	}

	// Get office status
	$status = $pop3->get_office_status();

	if ($status == false) {
		echo $pop3->error;
		continue;
	}

	$count = $status['count_mails'];

	for ($i = 1; $i <= $count; $i++) {
		$email = $pop3->get_mail($i);

		$email = parse_email($email);

		if ($email == false) {
			echo $pop3->error;
			continue;
		}

		// Check to see if the Message-ID is in our ids array.
		// Only announce if it's a new message and NOT in the existing array
		$testid = trim($email['headers']['Message-ID']);
		$testid = get_simple_email($testid);
		if (empty($testid) || $testid == " ") {
			// Try different spelling
			$testid = trim($email['headers']['Message-Id']);
			$testid = get_simple_email($testid);
		}
		if (empty($testid)) {
			print_r($email[headers]);
			$testid = $file_name;
		}

		if (!in_array($testid, $ids)) {
			// add this one to the ids array
			if (count($ids)==0) {
				$ids = array($testid);
			} else {
				array_push($ids, $testid);
			}
			// echo a few things to the terminal for monitoring purposes
			echo "Message-ID: [$testid]\n";
			$efrom = $email['headers']['From'];
			$efrom = get_simple_email($efrom);
			echo date("Y-m-d H:i:s") . " New messages from: $efrom\n";
			echo 'Subject: ' . $email['headers']['Subject'] . "\n\n";
			// send message to dcerouter if subject isn't in ignore list
			$found = 0;
			foreach ($ignore_subjects as $subj) { 
				if (eregi($subj, $email['headers']['Subject'])) { 
					$found = 1;
					break;
				}
			}
			if (!$found) { 	
				$message = "Email from $efrom regarding " . $email['headers']['Subject'];
				exec("/usr/pluto/bin/MessageSend localhost 0 -305 1 809 9 \"$message\" 70 \"\" 182 10 251 0");
				echo "Broadcasted this message to dcerouter.\n";
				// Let the pop up show for multiple messages
				sleep(10);
			}
		}

	}

	if ($count == 0) {
		echo date("Y-m-d H:i:s") . " There are no new e-mails\n";
		// This is a good place to clear out the data file since the mailbox is now empty
		if (file_exists($file_name)) {
			@unlink($file_name);
		}
	}

	// See if there's been any additions to the ids array
	// and if so, write back the new info
	$new_count = (count($ids));
	if ($orig_count < $new_count) {
		write_file($file_name, $ids);
	}

	$pop3->close();

   }
   unset($msgids);
   unset($ids);
   sleep($waitfor);
}


function parse_email ($email) {
    // Split header and message
    $header = array();
    $message = array();

    $is_header = true;
    foreach ($email as $line) {
        if ($line == '<HEADER> ' . "\r\n") continue;
        if ($line == '<MESSAGE> ' . "\r\n") continue;
        if ($line == '</MESSAGE> ' . "\r\n") continue;
        if ($line == '</HEADER> ' . "\r\n") { $is_header = false; continue; }

        if ($is_header == true) {
            $header[] = $line;
        } else {
            $message[] = $line;
        }
    }

    // Parse headers
    $headers = array();
    foreach ($header as $line) {
        $colon_pos = strpos($line, ':');
        $space_pos = strpos($line, ' ');

        if ($colon_pos === false OR $space_pos < $colon_pos) {
            // attach to previous
            $previous .= "\r\n" . $line;
            continue;
        }

        // Get key
        $key = substr($line, 0, $colon_pos);

        // Get value
        $value = substr($line, $colon_pos+2);
        $headers[$key] = $value;

        $previous =& $headers[$key];
    }

    // Parse message
    $message = implode('', $message);

    // Return array
    $email = array();
    $email['message'] = $message;
    $email['headers'] = $headers;

    return $email;
}

function get_simple_email($str) {

	$open = strpos($str, "<");
	$close = strpos($str, ">");

	if (($open === false) && ($close === false)) {
		return $str;
	}

	return substr($str, $open + 1, $close - $open - 1);

}


function read_file($name) {

	if (file_exists($name)) {
		$ids = file($name);
		return $ids;
	} else { 
		return false;
	}

}


function write_file($name, $data) {

	if ($fd = @fopen($name, "w")) {
		foreach ($data as $line) {
			if (!empty($line)) { 
				fwrite($fd, $line . "\n");
			}
		}
		fclose($fd);
		return true;
	} else {
		return false;
	}
}

?>


When you put the two files (in the same directory) on the core, make sure the user you start the script with has permission to write files in that directory, otherwise it won't be able to keep a tally of the messages it has already seen.