calebcall has asked for the wisdom of the Perl Monks concerning the following question:

I'm working on a script that will run nightly against a mailbox and pull all the messages for that day. Ideally what I would like to do is pull the messages, count how many times each message appears and only show messages (the the number of times they appear) that are in there more than once. Then I'd like to delete all messages that are older than a day to keep this mailbox cleaned up.

Right now I have written a PHP script that is pulling the mail. Then I call the php script with a perl script, pipe the results to | sort -rnf | uniq -ic | sort -rnf | grep -v '\ \ 1\ ' which is kind of doing what I want...in a hacktastic way.

I'm working towards rewriting the script in perl. I'm fairly new to perl so bear with me. So far I've been able to come up with something that will pull messages that have today's date in the header. Without piping to another script like I'm currently doing, is there a way to sort today's messages, give a count of each, and email the results, then delete any messages that are not today's?

This is what I'm working with so far (again, I'm new to this so if there is a better way to accomplish what I'm trying to do, feel free to let me know.)

#!/usr/bin/perl -w use strict; use warnings; use Net::IMAP::Simple; use Email::Simple; my $host = '<server>'; my $user = '<user>'; my $pass = '<pass>'; # Create the object my $imap = Net::IMAP::Simple->new($host) ; # Log on if(!$imap->login($user,$pass)){ print STDERR "Login failed: Unable to login. \n"; exit(64); } # Print the subject's of all the messages in the INBOX my $newm = $imap->select('INBOX'); for(my $i = 1; $i <= $newm; $i++) { my $es = Email::Simple->new(join '', @{ $imap->top($i) } ) +; my $messages = $es->header('Subject')."\n"; my $date = $es->header('Date'); my $today =`date | awk '{print \$1",",\$3,\$2,\$6}'`; chomp $messages; chomp $date; chomp $today; if ($date =~ m/^$today/) { print "$messages \n"; } } $imap->quit;

I've tried adding an else to my if that prints my messages out: else { $imap->delete($messages); } So it would delete any messages that do not have today's date. However I think the $imap->delete is looking for the message number and not the subject that I'm passing to it. So how can I get the message number to pass to it?

  • Comment on Net::IMAP::Simple and Email::Simple printing, sorting, emailing, and deleting messages.
  • Select or Download Code

Replies are listed 'Best First'.
Re: Net::IMAP::Simple and Email::Simple printing, sorting, emailing, and deleting messages.
by sierpinski (Chaplain) on May 01, 2010 at 18:07 UTC
    Did you look at this (cpan.org), specifically the section on 'Searching'? There's an argument you can pass it that can be used as a filter, and that returns message numbers. Then you should be able to do what you want to do.

    Hope that helps.