I’m using Mail::POP3Client for its simplicity and would like to pull the headers of the latest n messages (5 in my code).
This will be a webscript and on page load the latest 5 emails are downloaded and parsed (their subjects and senders)
But the way it is now I get some assortment of emails from July instead of my latest 5 (I have plenty of emails before July as well). Apparently my $email_count = $pop->Count; is just count and not an index-type value?
for (my $i = $email_count; $i >= $email_count-5; $i--) {
foreach ($pop->Head($i)) {
if (/^(From):\s+/i) { $FROM = $_; }
if (/^(Subject):\s+/i) { $SUBJECT = $_; }
if (/^(Date):\s+/i) {
$TIME = $_;
$TIME =~ s/Date: (.*)/$1/;
my $tstamp = str2time($TIME);
# $TIME = $tstamp;
$TIME = scalar localtime($tstamp);
my @fromsubj;
$fromsubj[0] = $FROM;
$fromsubj[1] = $SUBJECT;
$subject{$TIME} = [@fromsubj];
}
}
print "Index: $i \n";
}
print Dumper(%subject);
print "\n";
print Dumper(%from);
print "Mails $email_count to ".($email_count-5);
Output:
Index: 4030
Index: 4029
Index: 4028
Index: 4027
Index: 4026
Index: 4025
$VAR1 = 'Thu Jul 26 09:01:07 2012';
$VAR2 = [
'From: Person one ',
'Subject: Fwd: test '
];
$VAR3 = 'Tue Jul 24 15:09:43 2012';
$VAR4 = [
'From: person two ',
'Subject: subj '
];
(And so on)
....
Count 4030 4020
How can I pull the latest emails only? Is this possible with POP/this module at all, if not what could I use instead?
This should help a lot – http://www.ietf.org/rfc/rfc1939.txt. I’m not seeing anything about sorting by date in there, or anything about sorting at all for that matter.
I developed an IMAP solution that had to handle a large amount of mail. Since there is no way to limit results, I had to fill an array with tons of ids, and then iterate the array in chunks. When I was developing this solution, POP was unreliable and slow. IMAP definitely isn’t perfect, but developing with it was a lot smoother than pop.
Since you’re say you’re not dealing with that much data, I would just pull all of the data from the mailbox, then sort it by date and limit it in Perl.