The asnwer to How to send an email with PowerShell is very simple: Send-MailMessage! I love this command! It’s simple and it works very well.
I have tested this only on PS 3.0, but the command is available for 4.0 and 5.0 as well. I’m not going to write down the whole lot of informations, if you want to have a deeper knoledge about this command, have a look at Microsoft’s Send-MailMessage CMDLET.
If you’re looking for a simple explaination including examples and issues I found with this command, keep reading.
It is important to understand the fact that you will require an SMTP server to connect to! I’ve only tested this with Microsoft Exchange 2010 so far.
Let’s say we want to send an email from email@example.com, to firstname.lastname@example.org, with Test001 as a subject, using mysmtp01.contoso.com as smtp server and an HTML body (Hello,<BR /> this is a test.<BR />Kind Regards,<BR />PowerShell).
Send-MailMessage -To "email@example.com" -Subject "Test001", -Body "Hello,<BR /> this is a test.<BR />Kind Regards,<BR />PowerShell" -From "firstname.lastname@example.org" -BodyAsHtml -SmtpServer "mysmtp01.contoso.com"
That simple! You can also attach a file with -Attachments “data.csv”. As I said, I won’t be covering all of the options here but this is how to send an email with PowerShell!
I have had issues with our Exchange Environment to send emails every now and then, they would fail with this error: Unable to read data from the transport connection: net_io_connectionclosed.
The weird thing is that if I am to try to re-send this command a second later, it would get the email sent.
I found somebody on the internet having the same issue and the way he resolved it was better than the way I was working on. What this piece of code below does is very simple: it tries to send the email 5 times and if it fails 5 times then it’ll quit. (more…)