#!/usr/bin/env perl use strict; use warnings; use LWP::UserAgent; use XML::Twig; my $has_iso8601 = eval { require DateTime::Format::ISO8601 }; # returns true if present #### user defined variables: specify user/pass on cmd line or in quotes below my $gmail_user = (defined($ARGV[0])) ? $ARGV[0] : ''; my $password = (defined($ARGV[1])) ? $ARGV[1] : ''; my $max_char = '25'; # num. chars to truncate after. 0 = no truncation # check that username and password are set unless ( $gmail_user && $password ) { print "Usage: gmail.pl \n"; print "or set the \$username and \$password variables in the script\n"; exit; } # setup feed reader my $ua = LWP::UserAgent->new; $ua->agent('gmail.pl/1.0'); $ua->timeout('20'); # seconds $ua->credentials( 'mail.google.com:443', 'New mail feed', $gmail_user, $password, ); # get feed xml my $xmlresponse = $ua->get('https://mail.google.com/mail/feed/atom'); die($xmlresponse->status_line, "\n") unless ($xmlresponse->is_success); my $xml = ($xmlresponse->content); # setup parser and parse the xml my @emails; my $parser = new XML::Twig( TwigHandlers => { entry => \&email, } ); $parser->parse($xml); foreach my $email (@emails) { print "From: $email->{author}\n"; printf('%-5s %s', "Re:", "$email->{title}\n"); print "Sent: $email->{time}\n\n"; } # runs when a "entry" tag is encountered - 1 time per new email sub email { my ($twig, $element) = @_; push (@emails, ( { 'title' => shorten( $element->first_child_text('title') ), 'author'=> shorten( $element->first_child('author')->first_child_text('name') ), 'time' => time_format( $element->first_child_text('issued') ), } ) ); } sub time_format { my $issued = shift @_; $issued =~ /T(\d+):/; # gmail uses 1-24 for hours instead of if ($1 == 24) { # 0-23. the module chokes if hour = 24, $issued =~ s/T\d+:/T00:/; # so replace it with 0 if present. } if ($has_iso8601) { my $dt = DateTime::Format::ISO8601->parse_datetime($issued); $dt->set_time_zone('local'); my $time = $dt->strftime("%a, %b %d @ %r"); # DOW, month, day @ hh:mm::ss } else { my @times = split(/T/, $issued); my $time = join " ", @times; } } # truncates the string at $max_char if it is too long to fit in the space allotted sub shorten { my $string = shift @_; if ($max_char) { if (length $string > $max_char) { return substr($string, 0, $max_char-3) . "..."; } } return $string; } # gmail.pl v1.0 1/3/06