Sending Email via PowerShell and EWS

Just a sample script. I forgot that the message body needed to be converted to a string format and, as this script was being called by a back end process, it took me a while to figure out what the error was.



Add-Type -Path ‘F:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll’

#Create the EWS service object
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService -ArgumentList Exchange2010_SP1

#Set the credentials for Exchange Online
#$service.Credentials = New-Object Microsoft.Exchange.WebServices.Data.WebCredentials -ArgumentList `
#$Credential.UserName, $Credential.GetNetworkCredential().Password
$service.UseDefaultCredentials = $true

#Determine the EWS endpoint using autodiscover
#$service.AutodiscoverUrl($Credential.UserName, {$true})

#Get the email body
$body = Get-Content “C:\Files\EmailTemplate.htm”
$body = $body -replace “Placeholder”, $Placeholder

#Have to convert the object to a string to use in the mail body.
[string]$msgBody = $body

#Create the email message and set the Subject and Body
$message = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage -ArgumentList $service
$message.Body.BodyType = ‘HTML’
$message.From = “”
$message.Subject = “A message for you”
$message.Body = $msgBody


#Send the message and save a copy in the users Sent Items folder (Alt is message.Send which will not save a copy.)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s