The following snippet allows a user to find thru perl a certain email that complies with user-specified search criteria. As the function is very generic, the user can search in any field he likes.
All he needs to do is call the function as follows :
getInboxEmails('Subject'=>'','To'=>'','SenderName'=>'','Body'=>'zs');
He can specify which field to search, as long as they exist in the Outlook Object Model. As soon as a criterion isn't met in a field for a given mail then the search goes on to the next mail without reading that mail's other fields...
Please feel free to comment on the code - I new to the perl world and I may not be programming efficiently - I just enjoy OLE stuff !!!
Enjoy this bit, more to come, Foggy Bottoms.
sub getInboxEmails
# this method returns a list of all the mails contained in the Inbox f
+older
# that meet the search criteria specified in the filter
{
my %filter = @_;
if ( my $outlook = Win32::OLE->GetActiveObject('Outlook.Application
+'))# connect to outlook application
{
# connect and browse Inbox
my $namespace = $outlook->GetNameSpace("MAPI");
my $inbox = $namespace->GetDefaultFolder(olFolderInbox);
# my $inbox = $namespace->GetFolderFromID("Inbox\\INSA\\amis");
# returns a MAPIfolder object
my $inboxEmails = undef;
my $found = 0;
for (my $i=1;$i<=$inbox->items->Count();$i++)
# scan each item and make sure it's an email
# CAUTION : Outlook's item index starts at one and goes to the n
+umber of items found instead
# of going from 0 to (n-1)...
{
my $item = $inbox->items->Item($i);
my $email = undef;
if ($item->{Class}==olMail)# is it an email ? olMail = 43
{
foreach my $key (keys %filter)
{
# print "key : $key \n"; # debug purpose
if ($key ne "Body")# Body needs a special treatment as
+it can be text or HTML
{
$email->{$key} = $item->{$key};
}
else
{
if (not($email->{"Body"}=$item->{HTMLBody}))
{
$email->{"Body"}=$item->{Body}
}
}
# if mail meets criterion
$found = ($email->{$key} =~/$filter{$key}/is);
if (not $found)
{
last; # exits the foreach loop at this point
}
}
if ($found) # if still true then mail meets all criteria s
+pecified
{
$inboxEmails->{$i}=$email;
# print "found one ($i)...\n" # debug purpose
}
}
}
return $inboxEmails;
}
return (undef); # if code reaches this line then it hasn't reached
+the other return
}# implying either the program's not open or there's no document.