[problem]
How to use Perl to connect to MS Outlook. Then descend through given folders and save items to disk, as text files.
[/problem]
[solution]
I wrote this some time ago, to traverse predefined outlook mail folders, saving items with given subject to text.
Requires WIN32:OLE perl module (which comes with activeperl by default).
Hardcoded is the upload and uploaded mail folders. Also a subject that contains – pattern: upload.
I used one outlook rule to move items from a specific source, with this subject into upload.
[/solution]
[example]
Here is the code – if you have any dramas with it, leave a comment.
#!perl
use Win32::OLE qw(in with);
use Win32::OLE::Const 'Microsoft Outlook';
# Connect to a running version of Outlook
eval { $Outlook =
Win32::OLE->GetActiveObject('Outlook.Application')
};
die "Outlook not installed" if $@;
# If that fails start up Outlook
unless(defined $Outlook) {
$Outlook =
Win32::OLE->new('Outlook.Application', 'Quit')
or die "Opps, cannot start Outlook";
}
# This appears to return a ref to the object
$namespace = $Outlook->GetNamespace('MAPI');
$thisFolder=$namespace->Folders("Mailbox - mailboxna")->
Folders('upload');
$toFolder=$namespace->Folders("Mailbox - mailboxna")->
Folders('uploaded');
# Workaround to be able to extract key/value pairs
%thisHash=%{$thisFolder};
$name=$thisHash{'Name'};
# This is the number of items in designated folder
$count=$thisHash{'Items'}{'Count'};
open(LOGFH,">> ol_save_to_text.log")
or die("cannot open log filen");
# Drop out if there are no mail items in this folder
if($count > 0) {
print LOGFH "Count: $count for $namen";
$filename='yourname';
open(FH,"> $filename")
or die ("cannot open $filenamen");
for($i=1;$i<=$count;$i++) {
print LOGFH "Count: $countn";
$oItems=$thisFolder->Items(1);
%thisItem=%{$oItems};
$subject=$thisItem{'Subject'};
if($subject =~ /pattern: upload/) {
print LOGFH "$i: $subjectn";
$body=$thisItem{'Body'};
print FH "$body";
$oItems->Move($toFolder);
} else {
$nonitem+=1;
}
$oItems->Move($toFolder);
}
} else { print LOGFH "No Files to Processn"; }
close(LOGFH);
1;
[/example]
[reference]
Microsoft Outlook Keyboard Shortcuts – Courtesy of RNIB
[tags]MS Outlook OLE Perl, MS Outlook, OLE, Perl win32, cygwin, Perl, Perl Coding School[/tags]
[/reference]
If you have found my website useful, please consider buying me a coffee below 😉