5 =head1 NAME $RCSfile: announceEmail.pl,v $
7 Monitors an IMAP Server and announce incoming emails by extracting the subject
8 line and from line and then pushing that into "GoogleTalk".
16 Andrew DeFaria <Andrew@DeFaria.com>
24 Thu Apr 4 13:40:10 MST 2019
28 $Date: 2019/04/04 13:40:10 $
34 Usage: announceEmail.pl [-usa|ge] [-h|elp] [-v|erbose] [-de|bug]
35 [-use|rname <username>] [-p|assword <password>]
37 [-an|nouce] [-ap|pend] [-da|emon] [-n|name <name>]
38 [-uses|sl] [-useb|locking]
41 -usa|ge Print this usage
43 -v|erbose Verbose mode (Default: -verbose)
44 -de|bug Turn on debugging (Default: Off)
46 -user|name User name to log in with (Default: $USER)
47 -p|assword Password to use (Default: prompted)
48 -i|map IMAP server to talk to (Default: defaria.com)
50 -an|nounce Announce startup (Default: False)
51 -ap|pend Append to logfile (Default: Noappend)
52 -da|emon Run in daemon mode (Default: -daemon)
53 -n|ame Name of account (Default: imap)
54 -uses|sl Whether or not to use SSL to connect (Default: False)
55 -useb|locking Whether to block on socket (Default: False)
58 $SIG{USR1}: Toggles debug option
59 $SIG{USR2}: Reestablishes connection to IMAP server
63 This script will connect to an IMAP server, login and then monitor the user's
64 INBOX. When new messages arrive it will extract the From address and Subject
65 from the message and compose a message to be used by "Google Talk" to announce
66 the email. The message will be similar to:
68 "<From> emailed <Subject>"
81 use lib "$FindBin::Bin/../lib";
89 my $defaultIMAPServer = 'defaria.com';
96 'You have received a new message',
97 'Hey I found this in your inbox',
98 'For some unknown reason this guy send you a message',
99 'Did you know you just got a message',
101 'You received a communique',
102 'I was looking in your inbox and found a message',
103 'Not sure you want to hear this message',
105 "What's this? A new message",
108 my $icon = '/home/andrew/.icons/Thunderbird.jpg';
109 my $timeout = 5 * 1000;
112 usage => sub { pod2usage },
113 help => sub { pod2usage(-verbose => 2)},
114 verbose => sub { set_verbose },
115 debug => sub { set_debug },
117 username => $ENV{USER},
118 password => $ENV{PASSWORD},
119 imap => $defaultIMAPServer,
125 my $cmd = "notify-send -i $icon -t $timeout '$msg'";
132 notify 'Turning off debugging';
135 notify ('Turning on debugging');
145 my $msg = "Re-establishing connection to $opts{imap} as $opts{username}";
154 $SIG{USR1} = \&interrupted;
155 $SIG{USR2} = \&restart;
158 $IMAP->select('inbox') or
159 $log->err("Unable to select inbox: " . get_last_error(), 1);
161 return map { $_=> 0 } @{$IMAP->search('not', 'seen')};
165 $log->dbug("Connecting to $opts{imap} as $opts{username}");
167 # Destroy any old connections
170 $IMAP = Mail::IMAPTalk->new(
171 Server => $opts{imap},
172 Username => $opts{username},
173 Password => $opts{password},
174 UseSSL => $opts{usessl},
175 UseBlocking => $opts{useblocking},
176 ) or $log->err("Unable to connect to IMAP server $opts{imap}: $@", 1);
178 $log->dbug("Connected to $opts{imap} as $opts{username}");
180 # Focus on INBOX only
181 $IMAP->select('inbox');
183 # Setup %unseen to have each unseen message index set to 0 meaning not read
185 %unseen = unseenMsgs;
192 $log->dbug("Top of MonitorMail loop");
194 # First close and reselect the INBOX to get its current status
196 $IMAP->select('INBOX')
197 or $log->err("Unable to select INBOX - ". $IMAP->errstr(), 1);
199 $log->dbug("Closed and reselected INBOX");
200 # Go through all of the unseen messages and add them to %unseen if they were
201 # not there already from a prior run and read
202 my %newUnseen = unseenMsgs;
204 # Now clean out any messages in %unseen that were not in the %newUnseen and
205 # marked as previously read
206 $log->dbug("Cleaning out unseen");
208 if (defined $newUnseen{$_}) {
210 delete $newUnseen{$_};
217 $log->dbug("Processing new unseen messages");
218 for (keys %newUnseen) {
221 my $envelope = $IMAP->fetch($_, '(envelope)');
222 my $from = $envelope->{$_}{envelope}{From};
223 my $subject = $envelope->{$_}{envelope}{Subject};
224 $subject //= 'Unknown subject';
226 # Extract the name only when the email is of the format "name <email>"
227 if ($from =~ /^"?(.*?)"?\s*\<(\S*)>/) {
228 $from = $1 if $1 ne '';
231 if ($subject =~ /=?\S+?(Q|B)\?(.+)\?=/) {
232 $subject = decode_base64($2);
235 # Google Talk doesn't like #
239 my $logmsg = "From $from $subject";
241 my $greeting = $greetings[int rand $#greetings];
242 my $msg = "$greeting from $from... $subject";
245 my $hour = (localtime)[2];
247 # Only announce if after 6 Am. Note this will announce up until
248 # midnight but that's ok. I want midnight to 6 Am as silent time.
249 $log->dbug("About to speak/log");
251 $log->dbug("Calling speak");
255 $log->msg("$logmsg [silent]");
262 my $startTime = time;
264 # Re-establish callback
265 $log->dbug("Evaling idle");
266 eval { $IMAP->idle(\&MonitorMail) };
268 # If we return from idle then the server went away for some reason. With Gmail
269 # the server seems to time out around 30-40 minutes. Here we simply reconnect
270 # to the imap server and continue to MonitorMail.
277 # If $log is not yet defined then the exit is not unexpected
279 my $msg = "$FindBin::Script ending unexpectedly!";
305 unless ($opts{password}) {
306 verbose "I need $opts{username}'s password";
307 $opts{password} = GetPassword;
310 $opts{name} //= $opts{imap};
312 if ($opts{username} =~ /.*\@(.*)$/) {
317 # Perl complains if we reference $DB::OUT only once
319 EnterDaemonMode unless defined $DB::OUT or get_debug;
324 path => '/var/local/log',
325 name => "$Logger::me.$opts{name}",
326 timestamped => 'yes',
327 append => $opts{append},
332 if ($opts{username} =~ /(.*)\@/) {
335 $opts{user} = $opts{username};
338 my $msg = "Now monitoring email for $opts{user}\@$opts{name}";
340 speak $msg, $log if $opts{announce};
346 # Should not get here
347 $log->err("Falling off the edge of $0", 1);