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] [-da|emon]
35 [-use|rname <username>] [-p|assword <password>]
39 -usa|ge: Print this usage
41 -v|erbose: Verbose mode (Default: -verbose)
42 -de|bug: Turn on debugging (Default: Off)
43 -da|emon: Run in daemon mode (Default: -daemon)
44 -user|name: User name to log in with (Default: $USER)
45 -p|assword: Password to use (Default: prompted)
46 -n|ame: Name of account (Default: imap)
47 -i|map: IMAP server to talk to (Default: defaria.com)
48 -uses|sl: Whether or not to use SSL to connect (Default: False)
49 -useb|locking Whether to block on socket (Default: False)
50 -a-nnounce Announce startup (Default: False)
54 This script will connect to an IMAP server, login and then monitor the user's
55 INBOX. When new messages arrive it will extract the From address and Subject
56 from the message and compose a message to be used by "Google Talk" to announce
57 the email. The message will be similar to:
59 "<From> emailed <Subject>"
72 use lib "$FindBin::Bin/../lib";
80 my $defaultIMAPServer = 'defaria.com';
87 'You have received a new message',
88 'Hey I found this in your inbox',
89 'For some unknown reason this guy send you a message',
90 'Did you know you just got a message',
92 'You received a communique',
93 'I was looking in your inbox and found a message',
94 'Not sure you want to hear this message',
99 usage => sub { pod2usage },
100 help => sub { pod2usage(-verbose => 2)},
101 verbose => sub { set_verbose },
102 debug => sub { set_debug },
104 username => $ENV{USER},
105 password => $ENV{PASSWORD},
106 imap => $defaultIMAPServer,
114 $log->msg("Turning off debugging");
117 $log->msg("Turning on debugging");
124 $SIG{USR1} = \&interrupted;
127 $IMAP->select('inbox') or
128 $log->err("Unable to select inbox: " . get_last_error(), 1);
130 return map { $_=> 0 } @{$IMAP->search('not', 'seen')};
134 $log->dbug("Connecting to $opts{imap} as $opts{username}");
136 $IMAP = Mail::IMAPTalk->new(
137 Server => $opts{imap},
138 Username => $opts{username},
139 Password => $opts{password},
140 UseSSL => $opts{usessl},
141 UseBlocking => $opts{useblocking},
142 ) or $log->err("Unable to connect to IMAP server $opts{imap}: $@", 1);
144 $log->dbug("Connected to $opts{imap} as $opts{username}");
146 # Focus on INBOX only
147 $IMAP->select('inbox');
149 # Setup %unseen to have each unseen message index set to 0 meaning not read
151 %unseen = unseenMsgs;
159 # First close and reselect the INBOX to get its current status
161 $IMAP->select('INBOX')
162 or $log->err("Unable to select INBOX - ". $IMAP->errstr(), 1);
164 # Go through all of the unseen messages and add them to %unseen if they were
165 # not there already from a prior run and read
166 my %newUnseen = unseenMsgs;
168 # Now clean out any messages in %unseen that were not in the %newUnseen and
169 # marked as previously read
171 if (defined $newUnseen{$_}) {
173 delete $newUnseen{$_};
180 for (keys %newUnseen) {
183 my $envelope = $IMAP->fetch($_, '(envelope)');
184 my $from = $envelope->{$_}{envelope}{From};
185 my $subject = $envelope->{$_}{envelope}{Subject};
186 $subject //= 'Unknown subject';
188 # Extract the name only when the email is of the format "name <email>"
189 if ($from =~ /^"?(.*?)"?\s*\<(\S*)>/) {
190 $from = $1 if $1 ne '';
193 if ($subject =~ /=?\S+?(Q|B)\?(.+)\?=/) {
194 $subject = decode_base64($2);
197 # Google Talk doesn't like #
201 my $logmsg = "From $from $subject";
203 my $greeting = $greetings[int rand $#greetings];
204 my $msg = "$greeting from $from... $subject";
207 my $hour = (localtime)[2];
209 # Only announce if after 6 Am. Note this will announce up until
210 # midnight but that's ok. I want midnight to 6 Am as silent time.
215 $log->msg("$logmsg [silent]");
221 # Re-establish callback
222 eval { $IMAP->idle(\&MonitorMail) };
224 # If we return from idle then the server went away for some reason. With Gmail
225 # the server seems to time out around 30-40 minutes. Here we simply reconnect
226 # to the imap server and continue to MonitorMail.
227 $log->dbug("MonitorMail: Connection to $opts{imap} ended. Reconnecting");
229 # Destroy current IMAP connection
230 $log->dbug("MonitorMail: Destorying IMAP connection to $opts{imap}");
234 # Re-establish connection
237 $log->dbug("MonitorMail: Reconnected to IMAP server $opts{imap}");
239 # MonitorMail again - the dreaded goto! Seems the cleanest way to restart
240 # in this instance. I could call MonitorMail() recursively but that would
241 # leave junk on the stack.
242 $log->dbug('MonitorMail: Going back to the top of the loop');
246 return; # To make perlcritic happy
250 # If $log is not yet defined then the exit is not unexpected
252 my $msg = "$FindBin::Script ending unexpectedly!";
277 unless ($opts{password}) {
278 verbose "I need $opts{username}'s password";
279 $opts{password} = GetPassword;
282 $opts{name} //= $opts{imap};
284 if ($opts{username} =~ /.*\@(.*)$/) {
289 # Perl complains if we reference $DB::OUT only once
291 EnterDaemonMode unless defined $DB::OUT;
295 path => '/var/local/log',
296 name => "$Logger::me.$opts{name}",
297 timestamped => 'yes',
303 if ($opts{username} =~ /(.*)\@/) {
306 $opts{user} = $opts{username};
309 my $msg = "Now monitoring email for $opts{user}\@$opts{name}";
311 speak $msg, $log if $opts{announce};
317 # Should not get here
318 $log->err("Falling off the edge of $0", 1);