Monday, July 22, 2013

Creating Item Attachments with the EWS Managed API with Powershell

Item Attachments in EWS allow you to create an Attachment that is of a Rich Exchange type such as an EmailMessage, Task, Post, Contact etc or even your own custom form if your using these. Although one thing you can't do with an Item attachment is attach an existing Exchange Item.

To use ItemAttachments in Powershell you need to use reflection in .NET as it involves invoking a Generic Method which is not that straight forward in Powershell.

The following is an example of creating a Task as an Item Attachment in Powershell using reflection

  1. $mail = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage($service);  
  2. $AtColtype = ("Microsoft.Exchange.WebServices.Data.AttachmentCollection") -as "Type"  
  3. $Tasktype = ("Microsoft.Exchange.WebServices.Data.Task") -as "Type"  
  4. $methodInf = $AtColtype.GetMethod("AddItemAttachment");  
  5. $AddItmAttachMethod = $methodInf.MakeGenericMethod($Tasktype);  
  6. $TaskAttachment = $AddItmAttachMethod.Invoke($mail.Attachments,$null);  
  7. $TaskAttachment.Item.Subject = "Mondays Task"  
  8. $TaskAttachment.Item.StartDate = (Get-Date)  
  9. $TaskAttachment.Item.DueDate = (Get-Date).AddDays(7)  
  10. $TaskAttachment.Name = "Mondays Task"  
  11. $mail.Subject = "See the Attached Task"  
  12. $mail.ToRecipients.Add("")   
  13. $mail.SendAndSaveCopy()