#Option Explicit use strict; use warnings; use Win32::OLE qw(EVENTS); # Working with MAPI sessions needs other threading model # # Private Sub Application_NewMail() sub application_newmail { my ($server, $alias) = @_; # connect to mailbox of CN $alias using server $server my $mapikey = "$server\n$alias"; # # On Error GoTo GetAttachments_err #' Declare variables # Dim ns As NameSpace # Dim Inbox As MAPIFolder # Dim Item As Object # Dim Atmt As Attachment # Dim FileName As String # Dim i As Integer my $err; # Set ns = GetNamespace("MAPI") my $session = Win32::OLE->new(qw(MAPI.Session Logoff)) or return Win32::OLE->LastError(); # Try to logon with dynamic profile under current account. # This may need a reasonable current CDO on your machine. $session->Logon(undef,undef,undef,1,undef,undef,$mapikey); return $err if $err = Win32::OLE->LastError(); # Set Inbox = ns.GetDefaultFolder(olFolderInbox) my $inbox = $mapi->Inbox(); return $err if $err = Win32::OLE->LastError(); # i = 0 # As described in MSDN, relying on Count for (possibly) "big" collections (like items in folder) # can be problematic. Therefore we iterate with GetFirst/GetNext (see below) # 'Check Inbox for messages and exit of none found # If Inbox.Items.Count = 0 Then # Exit Sub # End If my $messages = $inbox->Messages() or return Win32::OLE->LastError(); my $filter = $messages->Filter() or return Win32::OLE->LastError(); $filter->{Unread} = 1; # Only unread messages $messages->Sort(); # default Sort is ASC on CdoPR_MESSAGE_DELIVERY_TIME return $err if $err = Win32::OLE->LastError(); #' Check each message for attachments # For Each Item In Inbox.Items for (my $msg = $messages->GetFirst(); $msg; $msg = $messages->GetNext()) { #' Save any attachments found # For Each Atmt In Item.Attachments my $atts = $msg->Attachments; if ($atts and my $count=$atts->Count) { # Count is O.K. for "small" collections while ($count) { my $atmt = $atts->Item($count) or next; # There shouldn't be a path in the name, but be paranoid # ' This path must exist! Change folder name as necessary. # If Left(Atmt.FileName, 10) = "Flat_file_" Then (my $f = $atmt->Name || '') =~ s#.*[:\\/]##; next if !$f or $f !~ /^Flat_file_/; # FileName = "G:\Input\" & Atmt.FileName my $outfile = "G:\\Input\\$f"; # Beware! Backslashes required here! # Atmt.SaveAsFile FileName $atmt->WriteToFile($OutFile); return $err if $err = Win32::OLE->LastError; --$count; # i = i + 1 # End If # Next Atmt } } # Next Item } } # end sub