Fetching all ‘From’ email addresses from an IMAP email account

Perl February 12th, 2008

If you want to back-up certain elements of your email account, this is not always very easy to do. For example you may not use your address book much (or never), but want to keep a backup of all of the email addresses that have sent messages to you.

Thanks to Mail::IMAPClient, this is pretty easy to do - just use the code below and add in your IMAP server, username and password details where appropriate:

PERL:
  1. #!/usr/bin/perl -w
  2. use strict;
  3. use Mail::IMAPClient::BodyStructure;
  4. use Mail::IMAPClient;
  5.  
  6. my $serv = '';
  7. my $usr  = '';
  8. my $pwd  = '';
  9.  
  10. # Open file for writing
  11. open (EMAILS, ">>imapemails.txt") or die "Error $!";
  12.  
  13. # Log into mail account
  14. my $imap = Mail::IMAPClient->new(Server=>$serv,User=>$usr,Password=>$pwd) or die "Error $!";
  15.  
  16. # Select necessary folder
  17. $imap->select("INBOX") or die "Cannot select the folder for $usr: $@\n";
  18.  
  19. # Get 'From' headers from all messages and print them to file
  20. for my $h (
  21.         values %{$imap->parse_headers( scalar($imap->search("ALL")) , "From")}
  22.     ) {
  23.         print EMAILS map { "$h->{$_}[0]\n"} keys %$h ;
  24.     }
  25. close EMAILS;
  26.  
  27. # Open file again for reading
  28. open (EMA2, "imapemails.txt") or die "Error $!";
  29.  
  30. # Root out duplicates and put into an array
  31. my @seen;
  32. while (<EMA2>) {
  33.     my $infile = $_;
  34.     chomp($infile);
  35.     push(@seen,$infile) unless (grep $_ eq $infile, @seen);
  36. }
  37.  
  38. close (EMA2);
  39.  
  40. # Print array to file, overwriting any duplicate data
  41. open (EMA3, ">imapemails.txt") or die "Error $!";
  42.  
  43. foreach my $em (@seen) {
  44.     print EMA3 "$em\n";
  45. }
  46. close EMA3;

Share and Enjoy:
  • Digg
  • del.icio.us
  • Furl
  • Slashdot
  • Technorati
  • YahooMyWeb
  • Google

Leave a Reply