scripts/mailbox_watcher.pl

108 lines
2.8 KiB
Perl
Executable File

#!/usr/bin/env perl
use Mail::IMAPClient;
use IO::File;
use Data::Dumper;
my $cfg = do ($ENV{'HOME'}."/.config/mailbox_watcher.pl") or die "Can't read configuration file";
my $cache_dir = $cfg->{cache_dir};
my $log_file = IO::File->new(">>".$cache_dir."/mailbox_watcher.log") or die "Can't open log file $!";
my $date = `date "+%Y-%m-%d %H:%M:%S"`;
chomp $date;
select $log_file;
printf "[%s] Mailbox watcher started\n", $date;
if ($cfg->{debug} == 1) {
$cfg->{server}{Debug} = 1;
$cfg->{server}{Debug_fh} = IO::File->new(
">".$cache_dir."/imap.log")
or die "Can't open imap log: $!\n";
}
# chomp the pass as it's given from an external script -> should do it directly
my $pass = $cfg->{server}->{Password};
chomp $pass;
$cfg->{server}->{Password} = $pass;
my $server = $cfg->{server};
if ($cfg->{debug} == 1) {
print Data::Dumper->Dump([$server]);
}
my $imap = Mail::IMAPClient->new(%$server)
or die ("Can't create imap object");
$imap->connect or die "No connection!";
$date = `date "+%Y-%m-%d %H:%M:%S"`;
chomp $date;
printf "[%s] Connected to IMAP server\n", $date;
my $fh = IO::File->new(">".$cache_dir."/imap_count");
select $fh;
foreach $box (@{$cfg->{boxes}}) {
my $r_count = 0;
defined($r_count = $imap->recent_count($box))
or die "Could not count ".$box." recent: $@\n";
if ($r_count > 0) {
$imap->select($box);
#$imap->unset_flag("\Recent", @{$imap->recent});
}
my $u_count = 0;
defined($u_count = $imap->unseen_count($box))
or die "Could not count ".$box." unseen: $@\n";
printf "%s\t%d/%d\n", ($box, $r_count, $u_count);
}
undef $fh;
select $log_file;
print "OK";
if ($cfg->{sms_send} == 1) {
my $fh = IO::File->new("<".$cache_dir."/imap_count")
or die "Can't open imap count file";
my $sms = "";
my $date = `date "+%Y-%m-%d %H:%M:%S"`;
chomp $date;
printf "[%s] Building the SMS to send\n", $date;
while (readline($fh)) {
if (not /\t0\//) {
s/\t/ /g;
s/ /:/g;
s/\n/\\n/g;
$sms .= $_;
print $sms;
}
else {
}
}
my $date = `date "+%Y-%m-%d %H:%M:%S"`;
chomp $date;
chomp $sms;
if (length $sms > 0) {
#printf "[%s] SMS to send : %s\n", ($date, $sms);
printf "[%s] Sending SMS to number : %s\n", ($date, $cfg->{sms_number});
my $tmp = `mktemp`;
my $tmp_fh = IO::File->new(">".$tmp) or die "Can't open temporary file";
# write sms into tmp file
select $tmp_fh;
print $sms;
select $log_file;
my $sys_call = $cfg->{sms_sender}.' '.$cfg->{sms_number}.' '.$tmp;
!system $sys_call;
!system "/usr/bin/rm $tmp";
}
else {
printf "[%s] No new message\n", ($date, $sms);
printf "%s, %d", ($sms, length $sms);
}
}
exit;