Some time ago
Gmail added IMAP support... and I thought it would be nice to see if Perl could cope with it.
Having used Mail::POP3Client and Mail::IMAPClient in the past, the latter was a natural choice for this challenge. The only thing is that Mail::IMAPClient does not support operations over SSL natively, even if it's possible to provide whatever socket we want to handle communications.
Things did not go smoothly, anyway, because I discovered that it doesn't suffice to simply create the socket and pass it to the client. After some debugging, I finally came to a working example:
#!/usr/bin/perl
use strict;
use warnings;
use Mail::IMAPClient;
use IO::Socket::SSL;
# Connect to the IMAP server via SSL and get rid of server greeting me
+ssage
my $socket = IO::Socket::SSL->new(
PeerAddr => 'imap.gmail.com',
PeerPort => 993,
)
or die "socket(): $@";
my $greeting = <$socket>;
my ($id, $answer) = split /\s+/, $greeting;
die "problems logging in: $greeting" if $answer ne 'OK';
# Build up a client attached to the SSL socket and login
my $client = Mail::IMAPClient->new(
Socket => $socket,
User => 'youraccount',
Password => 'yourpass',
)
or die "new(): $@";
$client->State(Mail::IMAPClient::Connected());
$client->login() or die 'login(): ' . $client->LastError();
# Do something just to see that it's all ok
print "I'm authenticated\n" if $client->IsAuthenticated();
my @folders = $client->folders();
print join("\n* ", 'Folders:', @folders), "\n";
# Say bye
$client->logout();
There were two tricky parts:
- the server sends you a greeting message that you have to consume by your own;
- you have to explicitly put the $client in connected state.
From now on... it's a matter of
RTFM!
Update: added a few comments in the code.
Update: thanks to markov, we now have some more features integrated, and using IO::Socket::SSL is more straightforward and DWIMmy:
#!/usr/bin/env perl
use strict;
use warnings;
use Mail::IMAPClient;
use IO::Socket::SSL;
# Connect to the IMAP server via SSL
my $socket = IO::Socket::SSL->new(
PeerAddr => 'imap.gmail.com',
PeerPort => 993,
)
or die "socket(): $@";
# Build up a client attached to the SSL socket.
# Login is automatic as usual when we provide User and Password
my $client = Mail::IMAPClient->new(
Socket => $socket,
User => 'youraccount',
Password => 'yourpass',
)
or die "new(): $@";
# Do something just to see that it's all ok
print "I'm authenticated\n" if $client->IsAuthenticated();
my @folders = $client->folders();
print join("\n* ", 'Folders:', @folders), "\n";
# Say bye
$client->logout();
Flavio
perl -ple'$_=reverse' <<<ti.xittelop@oivalf
Io ho capito... ma tu che hai detto?