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("user@domain.com")   
  13. $mail.SendAndSaveCopy()   


3 comments:

Unknown said...

Hi Glen,

first, thank you for sharing all those EWS informations

Would you know a way to create an ItemAttachment of type EmailMessage from an existing .msg file ?

Regards

Julien

Glen Scales said...

MSG files can only be used with the Office API's they are associated with so if you want to do anything with a MSG file you need to use MAPI via the Outlook OOM or Redemption/RDO

Cheers
Glen

Unknown said...

OK, thank you Glen