Sending emails using SMTP in Powershell


Hey folks,
In this short article I will show you how to send emails using a SMTP server in  Powershell. I’ve encountered a problem with an IIS server that was using a web service to connect to a SMTP server for sending emails. In order to debug the problem, I’ve created the following script for sending test emails:

function Mail{
Cls
Write-Host “Sending Email”

#SMTP server name that will be used for sending emails
$Server = “email.server”

#The following commands will initiate an mail object and will use the declared SMTP server
$message = new-object Net.Mail.MailMessage
$mail = new-object Net.Mail.SmtpClient($Server)

#Email
#The sender email address
$message.From = “user1@test.com”
#The receiver email address
$message.To.Add(“user2@test.com”)
#Email subject
$message.subject = “Subject”
#Email body
$message.body = “This is the body of the email”
#Command for sending email
$mail.Send($message)

Write-Host “Email Sent”

}

#Call the mail function
Mail

I’m using Windows PowerShell ISE for creating and testing scripts:

Windows PowerShell ISE

 

Descriptions can be found above each code line so I hope you’ve understood the script. As you can see, the code is pretty simple and intuitive. The only think you must assure is that the SMTP server can be reached and it’s operational. Save the code in a .ps1 file, change the values and test it on your environment. You can test the port using telnet. If you don’t know by now, SMTP uses port 25 for sending and receiving mails:

telnet SMTP
That’s it for this article, I hope it will help you when troubleshooting similar problems. If you think there is more to be added here don’t hesitate to leave a comment. Enjoy your day and stay tuned for the following articles.
Advertisements

3 thoughts on “Sending emails using SMTP in Powershell

  1. All you need to do is “search” PowerShell: get-help send-mailmessage -full

    In PowerShell 1.0 we needed to do what you've posted but I really hope you are running at least PowerShell 2.0. The only reason you would still need a function like this in 2.0 is if you need to specify a port other than 25. In PowerShell 3.0, the cmdlet was improved to allow you to specify a port.

    Like

    Reply

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s