How can I read messages in a Gmail account from Perl?
I have used the module Mail::Webmail::Gmail to read the new messages in my Gmail account.
I have written the following code for this purpose:
use strict;
use warnings;
use Data::Dumper;
use Mail::Webmail::Gmail;
my $gmail = Mail::Webmail::Gmail->new(
username => 'username', password => 'password',
);
my $messages = $gmail->get_messages( label => $Mail::Webmail::Gmail::FOLDERS{ 'INBOX' } );
foreach ( 开发者_StackOverflow@{ $messages } ) {
if ( $_->{ 'new' } ) {
print "Subject: " . $_->{ 'subject' } . " / Blurb: " . $_->{ 'blurb' } . "\n";
}
}
But it didn't print anything.
Can anyone help me in this or suggest any other module for this?
Thanks in advance.
This is taken almost word from word from the Net::IMAP::Simple POD:
use strict;
use warnings;
# required modules
use Net::IMAP::Simple;
use Email::Simple;
use IO::Socket::SSL;
# fill in your details here
my $username = 'user@example.com';
my $password = 'secret';
my $mailhost = 'pop.gmail.com';
# Connect
my $imap = Net::IMAP::Simple->new(
$mailhost,
port => 993,
use_ssl => 1,
) || die "Unable to connect to IMAP: $Net::IMAP::Simple::errstr\n";
# Log in
if ( !$imap->login( $username, $password ) ) {
print STDERR "Login failed: " . $imap->errstr . "\n";
exit(64);
}
# Look in the INBOX
my $nm = $imap->select('INBOX');
# How many messages are there?
my ($unseen, $recent, $num_messages) = $imap->status();
print "unseen: $unseen, recent: $recent, total: $num_messages\n\n";
## Iterate through unseen messages
for ( my $i = 1 ; $i <= $nm ; $i++ ) {
if ( $imap->seen($i) ) {
next;
}
else {
my $es = Email::Simple->new( join '', @{ $imap->top($i) } );
printf( "[%03d] %s\n\t%s\n", $i, $es->header('From'), $es->header('Subject') );
}
}
# Disconnect
$imap->quit;
exit;
You can use the Mail::POP3Client module. It is used to get the message from the Gmail account.
Have you tried doing some error checking with after you try an operation
if ($gmail->error())
{
print $gmail->error_msg();
}
I found that when I do it it results in:
Error: Could not login with those credentials - could not find final URL Additionally, HTTP error: 200 OK Error: Could not Login.
I believe it may be because this module was last updated in 2006 and gmail may have changed the way the logins work so it may no longer be able to access it.
What you could do if you don't just want to download new messages with pop3 is you can use Net::IMAP::Simple to access a gmail account via IMAP
精彩评论