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]
#!/usr/bin/perl -w
use strict;
use Mail::IMAPClient::BodyStructure;
use Mail::IMAPClient;

my $serv = ”;
my $usr = ”;
my $pwd = ”;

# Open file for writing
open (EMAILS, “>>imapemails.txt”) or die “Error $!”;

# Log into mail account
my $imap = Mail::IMAPClient->new(Server=>$serv,User=>$usr,Password=>$pwd) or die “Error $!”;

# Select necessary folder
$imap->select(“INBOX”) or die “Cannot select the folder for $usr: $@\n”;

# Get ‘From’ headers from all messages and print them to file
for my $h (
values %{$imap->parse_headers( scalar($imap->search(“ALL”)) , “From”)}
) {
print EMAILS map { “$h->{$_}[0]\n”} keys %$h ;
}
close EMAILS;

# Open file again for reading
open (EMA2, “imapemails.txt”) or die “Error $!”;

# Root out duplicates and put into an array
my @seen;
while () {
my $infile = $_;
chomp($infile);
push(@seen,$infile) unless (grep $_ eq $infile, @seen);
}

close (EMA2);

# Print array to file, overwriting any duplicate data
open (EMA3, “>imapemails.txt”) or die “Error $!”;

foreach my $em (@seen) {
print EMA3 “$em\n”;
}
close EMA3;
[/perl]

Comments are closed.