Archive for the ‘php’ Category

Getting all email addresses from an imap account

Friday, December 28th, 2007

I have need of grabbing all the email addresses (to, from, cc, bcc etc etc) from my current imap server.

The reason? spam. I’m moving my main email to this domain, it’s quiet and off the spammers radar, unlike orange.net.

However, I’d like to have a plain text file detailing all the adresses I’ve communicated with over the past few years, such that I can unsubsribe the lists I no longer read, inform my friends I’m moving address, change my online shopping registrations , build a white/blacklist for forwarding from the old email address, etc etc.

I was quite surprised how hard it was to google for a small program/utility that did such a thing, in fact I failed to find one.

I ended up in php’s imap functions documentation, and from there it was pretty quick to script it.

Job Jobbed, as they say. Except for the need to find some sort of nice code formatter for wordpress ….

<?php
$imapServer = “{imap.yourserver.com:143}”;
$userName = “your.username”;
$password = “secretsquirrel”;
$mbox = imap_open($imapServer,$userName ,$password );

$folders = imap_listmailbox($mbox, $imapServer, “*”);

imap_close($mbox);

if ($folders == false) {
die( “failed to get folders\n”);
} else {

$addressArray = array();

foreach ($folders as $val) {

$mbox = imap_open($val, $userName,$password );

$numMessages = imap_num_msg($mbox);

print(”there are $numMessages in the mailBox $val\n”);

for($i=1;$i<=$numMessages;$i++)

{
$headerInfo = imap_headerinfo ($mbox,$i);

foreach($headerInfo as $headerObj)
if(is_array($headerObj)){

foreach ($headerObj as $id => $object) {
if(isset($object->mailbox) && isset($object->host))
{
$address = (string)($object->mailbox . “@” . $object->host);
if(array_search($address,$addressArray )=== FALSE)
{
$addressArray [] = $address;
}
}
}
}

}

imap_close($mbox);

}
}
$numAddresses = count($addressArray);

for($i=0;$i<$numAddresses;$i++)
{
print($addressArray[$i].”\n”);
}

?>