Following up on the earlier post, “Send an Email from the Windows Command Prompt or Script…“
…While I’m somewhat picking up where I left off in Part 1, the situation in that earlier post had special requirements about how the email message had to be sent (controlled source, user interaction, etc.). But what if you don’t have those requirements? What if you simply want to send an email from a Windows workstation or Server?
Well, in that case, simply use PowerShell. Since version 2, PowerShell has included the
Send-MailMessage cmdlet for relatively easy mail sending from almost any modern computer.
Recently, I was telling somebody how do use this method to send messages in a script, and demonstrating the input details such as specifying the SMTP relay server. The person then asked me, “What if the SMTP server changes?” Hmm… Good point. So I whipped up a few extra lines to work around that problem, and the person thought I should post it here. Agreed!
Here is the script, put together as plainly as possible, with clearly named variables to help you understand what’s going on:
$MyRecipientEmailAddress = "Fake.Address@CoretekServices.com" $MySenderEmailAddress = "JPavlov@YourLinuxGuy.com" $MyRecipient = $MyRecipientEmailAddress.Split("@") $MyDestinationDomain = $MyRecipientEmailAddress.Split("@") $MyMxRecords = Resolve-DnsName -Type MX -Name $MyDestinationDomain $MyMxRecord = $MyMxRecords.NameExchange $MyMessageSubject = "This is a test" $MyMessageBody = "This is the message. Thanks! - Jeremy" Send-MailMessage -To "$MyRecipientEmailAddress" -SmtpServer "$MyMxRecord" -Subject "$MyMessageSubject" -Body "$MyMessageBody" -From "$MySenderEmailAddress"
Remember, the trick is not really the standard options of the cmdlet, but grabbing the possibly-changing MX record for the relay. This script will dynamically go and get the *current* first-listed MX record for the recipient, and just use that.
And I can almost hear you now, “…But Jeremy, aren’t you side-stepping the built-in fault-tolerance of the MX record?” Yes, a bit; you can absolutely add a little more code to this and make it aware of the MX ranking, and roll through them and validate until successful. Maybe I’ll do that in another post…
By the way, while it may not be obvious to you initially, note that I’m just specifying my recipient’s destination SMTP server as my
-SmtpServer. This *should* be fine in many/most cases. The destination server should be glad to receive and forward the email to the end user that is a part of its own system. However, some security protection may block this from happening, so be sure to know your destination first. In my/our case, this was actually being used in an internal system to a friendly destination. Your result may vary…
Now get out there and send those emails!