Tedy Vicente
Tedy Vicente

Reputation: 3

Forward emails with PowerShell and EWS Managed API

I have a PowerShell Script that uses EWS Managed API to fetch and processes specific emails from an inbox. If an email doesn't meet a condition its then forwarded to another inbox. the script works fine, but if it finds emails with attachments (that don't meet condition), it gets stuck to Draft folder and doesn't get sent. Any ideas?

The part of the code that forwards the emails.

    Else {
      $mail = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage($service)
        $OriginalEmail = $findResults.Items[0]
        $psPropset= new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::IdOnly) 
        $psPropset.Add([Microsoft.Exchange.WebServices.Data.ItemSchema]::MimeContent)
        $psPropset.Add([Microsoft.Exchange.WebServices.Data.ItemSchema]::Subject)
        $OriginalEmail.Load($psPropset)
        
        # Delete Received email after gathering the data
        $findResults.delete([Microsoft.Exchange.WebServices.Data.DeleteMode]::MoveToDeletedItems,$True)

        $AtColtype = ("Microsoft.Exchange.WebServices.Data.AttachmentCollection") -as "Type"
        $Emailtype = ("Microsoft.Exchange.WebServices.Data.EmailMessage") -as "Type"
        $methodInf = $AtColtype.GetMethod("AddItemAttachment");
        $AddItmAttachMethod = $methodInf.MakeGenericMethod($Emailtype);
        $EmailAttachment = $AddItmAttachMethod.Invoke($mail.Attachments,$null);
        $EmailAttachment.Item.MimeContent = $OriginalEmail.MimeContent
        $PR_Flags = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(3591, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer);
        $EmailAttachment.Item.SetExtendedProperty($PR_Flags,"1");
        $EmailAttachment.Name = $OriginalEmail.Subject;
        $mail.Subject = "$Subject";
        $mail.ToRecipients.Add($ForwardToEmail);
        $mail.SendAndSaveCopy();
        $mail.Close()
    }

Any help is appreciated.

Upvotes: 0

Views: 682

Answers (0)

Related Questions