Thursday, 1 October 2015

Send email with PowerShell

To send email using PowerShell is quite quick and easy and is a nice trick to be able to test the receive connectors and email relay settings on an Exchange server.

In this example, our Exchange server is called litex01.litwareinc.com, has the default receive connectors when Exchange is installed and is running Exchange 2013 CU10. We'll be sending email to the administrator mailbox which is administrator@litwareinc.com.

The command we will use is Send-MailMessage. This uses SMTP to submit an email to an SMTP server like an email server outside the organization will submit an email to your Exchange server and can be used as an alternative to using Telnet. 

Instructions are below:

1) Construct anonymous credentials

PowerShell 4.0 and later will use the logged in user's credentials to authenticate against the SMTP server. If you're using Powershell 3.0 or earlier then you can skip this step. If you're using PowerShell 4.0 then you need to construct anonymous credentials so run the commands below:


$anonUser = "anonymous"
$anonPass = ConvertTo-SecureString "anonymous" -AsPlainText -Force

$anonCred = New-Object System.Management.Automation.PSCredential($anonUser, $anonPass)




2) Send your email

The example below sends an email to the administrator account using anonymous authentication:


PowerShell 4.0 and later:

For Powershell 4.0 and later, you need to specify the anonymous credentials to prevent it using the credentials of the user you are using to run the PowerShell console:

Send-MailMessage -To administrator@litwareinc.com -From test@test.com -Subject "Test email - PowerShell 4.0" -Body "Hello World!" -SmtpServer litex01.litwareinc.com -Credential $anonCred




PowerShell 3.0 and earlier:

For PowerShell 3.0 and earlier, you can omit the -Credential parameter

Send-MailMessage -To administrator@litwareinc.com -From test@test.com -Subject "Test email - PowerShell 3.0" -Body "Hello World!" -SmtpServer litex01.litwareinc.com




3) Confirm your emails are delivered using OWA



Here we can see our emails are delivered. If this doesn't work for you then perhaps you should check your receive connector is configured correctly and do some other troubleshooting if needed but anyway, that's how you send email using PowerShell.


No comments:

Post a Comment