CUFP
polettix
Some time ago [http://www.gmail.com/|Gmail] added IMAP support... and I thought it would be nice to see if Perl could cope with it.
<p>Having used [cpan://Mail::POP3Client] and [cpan://Mail::IMAPClient] in the past, the latter was a natural choice for this challenge. The only thing is that [cpan://Mail::IMAPClient] does not support operations over SSL natively, even if it's possible to provide whatever socket we want to handle communications.
<p>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:<c>
#!/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 message
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();
</c>
There were two tricky parts:
<ul>
<li>the server sends you a greeting message that you have to consume by your own;</li>
<li>you have to explicitly put the <c>$client</c> in connected state.</li>
</ul>
From now on... it's a matter of [cpan://Mail::IMAPClient|RTFM]!
<p><b>Update</b>: added a few comments in the code.
<p><b>Update</b>: thanks to [markov], we now have some more features integrated, and using [dist://IO::Socket::SSL] is more straightforward and DWIMmy:<c>
#!/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();
</c>
<!-- Node text goes above. Div tags should contain sig only -->
<div class="pmsig"><div class="pmsig-439923">
<p align=right>Flavio <br />
perl -ple'$_=reverse' <<<ti.xittelop@oivalf</p>
<i>Io ho capito... ma tu che hai detto?</i>
</div></div>