in reply to Outlook OLE Delete Attachments

Ha. Well I remembered that I had written such a script a long time ago but had lost the code. Turns out I posted here for help on it in 2004, and I found the node in a dusty corner of the Monastery basement. Problem was that you have to use a Remove method rather than a Delete method. The working code is below for anyone else who's interested (sans the C-style loop, which really seems to bother some of the Brothers).

Now the odd thing is that the purpose of running this was to free up mailbox space, but after running it and deleting a couple hundred attachments, some large, my mailbox size didn't change at all. Need to consult the Exchange admin on that one.

#!/usr/bin/perl -w use strict; use Win32::OLE; use Win32::OLE::Variant; use Win32::OLE::Const 'Microsoft Outlook'; use Date::Manip; my $ol; eval {$ol = Win32::OLE->GetActiveObject('Outlook.Application')}; die "Outlook not installed" if $@; unless (defined $ol) { $ol = Win32::OLE->new('Outlook.Application', sub {$_[0]->Quit;}) or die "Cannot start Outlook"; } my $cutoffdate = ParseDate("December 31, 2012"); my $mailbox = seekFolder($ol->Session, 'foo@bar.com'); my $folder = seekFolder($mailbox, 'Sent Items'); my $end = $folder->Items->Count; for my $i (1..$end) { my $msg = $folder->Items($i); my $msgdate = getTimeStamp($msg->{ReceivedTime}); if (Date_Cmp($cutoffdate,$msgdate) == 1) { my $atch = $msg->Attachments; my $deleted = 0; if ($atch->Count) { while ($atch->Count) { $atch->Remove(1); $deleted++; } $msg->Save; } if ($deleted) { print UnixDate($msgdate,"%Y-%m-%d %i:%M:%S %p")," ",substr +($msg->{Subject},0,30)."... $deleted attachments deleted\n"; } } else { last; } } Win32::OLE->FreeUnusedLibraries(); sub seekFolder { my $obj = shift; my $target = shift; for (my $i = 1; $i <= $obj->Folders->Count; $i++) { if ( $obj->Folders->Item($i)->Name eq $target ) { return $obj->Folders->Item($i); } } } sub getTimeStamp { my ($var) = @_; my $timestamp = Win32::OLE::Variant->new(VT_DATE,$var); return ParseDate($timestamp->Date("yyyyMMdd").$timestamp->Time("HH +mmss")); }

Replies are listed 'Best First'.
Re^2: Outlook OLE Delete Attachments
by Lotus1 (Vicar) on Oct 18, 2014 at 17:24 UTC
    ... the C-style loop, which really seems to bother some of the Brothers).

    C-style for loops are wonderful and powerful when there is a purpose for them. But when Perl provides such powerful ways to simplify your code such as the foreach loop it is a shame not to use them.