[Powershell Script - EWS] Send an Email from a user mailbox Using EWS Managed API

As we are going to use the EWS make sure you met all the prerequisites before you plan to run this script.
  • Admin account should have application impersonation rights, you can follow this MSDN post to setup the permissions.
  • Install EWS managed API on system where you plan to run the script from, if API is not installed, download the same from here
To send an email msg using the EWS managed API we will be using "Microsoft.Exchange.WebServices.Data.EmailMessage" Class, please edit the Recipients details in the script below script.

#Setting up Email message Class 
$message = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage -ArgumentList $service
$message.Subject = "This Message has been Created by EWS - Sunil Chauhan"
$message.From = $mailbox
$message.ToRecipients.Add("testuser@domain.com")
$message.ToRecipients.Add("testuser1@domain.com")
$message.Body = "This is Test Message By Sunil Chauhan From EWS Client"
$message.SendAndSaveCopy()

Please find the full code below.

#Web Service Path
param(
$mailbox="User@YourDomain.com",
$userName="AdminID@YourDomain.com",
$password="Password"
)

#Importing WebService DLL
$EWSServicePath="C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll"
Import-Module $EWSServicePath

#Creating Service Object
$Service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService
$service.Credentials = New-Object Microsoft.Exchange.WebServices.Data.WebCredentials -ArgumentList $userName, $password
$EWSurl = "https://outlook.office365.com/EWS/Exchange.asmx"
$Service.URL = $EWSurl

#Setting up ImperSonated User
$ArgumentList = ([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SMTPAddress),$mailbox
$ImpUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId -ArgumentList $ArgumentList
$service.ImpersonatedUserId = $ImpUserId

#Setting up Email message Class
$message = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage -ArgumentList $service
#Creating and Saving Message in Draft Folder
$message.Subject = "This Message has been Created by EWS - Sunil Chauhan"
$message.From = $mailbox
$message.ToRecipients.Add("testuser@domain.com")
$message.ToRecipients.Add("testuser1@domain.com")
$message.Body = "This is Test Message By Sunil Chauhan From EWS Client"
$message.SendAndSaveCopy()

Comments