Reading Mail with POP3
Problem
You want to fetch mail from a POP3 server. This lets you write a program to summarize your unread mail, move it from a remote server to a local mailbox, or toggle between Internet and local mail systems.
Solution
Use the CPAN module Net::POP3:
$pop = Net::POP3->new($mail_server) or die "Can't open connection to $mail_server : $!\n"; defined ($pop->login($username, $password)) or die "Can't authenticate: $!\n"; $messages = $pop->list or die "Can't get list of undeleted messages: $!\n"; foreach $msgid (keys %$messages) { $message = $pop->get($msgid); unless (defined $message) { warn "Couldn't fetch $msgid from server: $!\n"; next; } # $message is a reference to an array of lines $pop->delete($msgid); }
Discussion
Traditionally, mail has been a three-party system: the MTA (Mail Transport Agent, a system program like sendmail) delivers mail to the spool, where it is read by the MUA (Mail User Agent, a program like mail). This dates from the days of big servers holding mail and users reading it through dumb terminals. As PCs and networks entered the picture, the need arose for MUAs like Pine to run on different machines than the one housing the spool. The Post Office Protocol (POP) implements efficient message listing, reading, and deleting over a TCP/IP session.
The CPAN module Net::POP3 is a POP client. That is, it lets your Perl
program act as an MUA. The first step in using Net::POP3 is to create
a new Net::POP3 object. Pass new
the name of the POP3 ...
Get Perl Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.