On handling email
Watching the popular Inbox Zero video would probally improve my email handling skills better. But this took less time and I wanted to play around with Net::XMPP;
#!/usr/bin/perl -l
use warnings;
use strict;
use Config::Simple;
use Linux::Inotify2;
use Email::Abstract;
use Net::XMPP; # aka Jabber and Gtalk
use POSIX;
my $DEBUG = 0;
our %config;
Config::Simple->import_from("$ENV{HOME}/.mailnotifyrc", \%config);
deamonize() unless $DEBUG;
my $inotify = new Linux::Inotify2
or die "Unable to create new inotify object: $!";
# Different Maildir implementations triggers different events"
# IN_MOVED_TO: rename("tmp/file","new/file")
# IN_CREATE: link("tmp/file", "new/file") && unlink("tmp/file")
#
# At this point the file should be written and closed.
$inotify->watch("$config{Maildir}/new", IN_MOVED_TO|IN_CREATE, sub {
my $e = shift;
my ($fh, $xmpp, $email, $message);
debug('Got event for ' . $e->fullname);
open $fh, "<", $e->fullname;
$email = new Email::Abstract join("", <$fh>);
close $fh;
$message = 'Mail from ' . $email->get_header('From') .
' concerning "' . $email->get_header('Subject') .'"';
debug("Getting ready to send [$message]");
my $sender = new Net::XMPP::JID ($config{Sender});
my $receiver = new Net::XMPP::JID ($config{Receiver});
$xmpp = new Net::XMPP::Client();
$xmpp->Connect( hostname => $sender->GetServer,
port => $config{port} || 5222,
tls => $config{usetls} || 0,
);
$xmpp->AuthSend( username => $sender->GetUserID,
password => $config{password},
resource => $sender->GetResource || 'mailnotify',
);
$xmpp->MessageSend( to => $receiver,
type => $config{MessageType} || 'chat',
body => $message,
);
$xmpp->Process(1);
$xmpp->Disconnect;
debug("Event done");
});
1 while $inotify->poll;
sub deamonize {
my $pid = fork();
if ($pid) {
exit 0;
}
### close all input/output and separate
### from the parent process group
open STDIN, '</dev/null' or die "Can't open STDIN from /dev/null: [$!]\n";
open STDOUT, '>/dev/null' or die "Can't open STDOUT to /dev/null: [$!]\n";
open STDERR, '>&STDOUT' or die "Can't open STDERR to STDOUT: [$!]\n";
### Change to root dir to avoid locking a mounted file system
### does this mean to be chroot ?
chdir '/' or die "Can't chdir to \"/\": [$!]";
### Turn process into session leader, and ensure no controlling terminal
POSIX::setsid();
}
sub debug { return unless $DEBUG; print STDERR for @_; }
__END__