Timo codes to use Powershell for sending SMTP with AUTH
I needed a way to send SMTP email using Powershell but my SMTP server requires authentication. Sending email to a SMTP server that requires authentication isn’t much harder than sending email to a server that doesn’t. We basically call 2 .NET objects instead of one. Of course we need to set some properties for each .NET object.
The 2 .NET objects are
System.Net.NetworkCredential
System.Net.Mail.SmtpClient
Here is the PS code with comments.
# Set the SMTP server, this needs to be done before you can call the .NET object
$smtpServer = "smtpserver.yourdomain.net"
# Call the .NET object for sending email System.Net.Mail.SmtpClient
# http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx
# not too helpful eh... it'd be nice if there were some PS examples.
# instead you can type this into a PS prompt $smtp | gm and at least get the methods and properties
$smtp = new-object System.Net.Mail.SmtpClient($smtpServer)
# Call the .NET object that will turn on Authentication functionality System.Net.NetworkCredential
$smtpauth = new-object System.Net.NetworkCredential
# set the properties of the .NET.NetworkCredential object
# see the available properties, methods etc of this object by
# type this at the PS prompt $smtpauth | gm
$smtpauth.UserName = "username"
$smtpauth.Password = "password"
# Here we are associating the .NET.NetworkCredential object and it's properties with
# the other .NET object we are using System.Net.Mail.SmtpClient.
# .Credentials is a property of the .NET object System.Net.Mail.SmtpClient
# Here we are associating the variable $smtpauth with the Properties we set
$smtp.Credentials = $smtpauth
# Lets set the From, To, Subject and Body in variables for scalability
$smtpFrom = "powershell-script@yourdomain.net"
$smtpTo = "timo@yourdomain.net"
$smtpSubject = "Powershell Email Test"
$smtpBody = "This is just some junk for the body of the email"
# Here we call the method .Send from System.Net.Mail.SmtpClient and fill in its parameters.
# You can see all the methods & properties by hammering this into the keyboard $smtp | gm
$smtp.Send($smtpFrom, $smtpTo, $smtpSubject, $smtpBody)
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment