Wednesday, May 29, 2013

Sending Email using Powershell

Here is an interesting study into sending an email via .NET or using native PowerShell v3 Cmdlets. Obviously the native way is much simpler and I have personally found it to be more reliable.
.NET Way

#SMTP server name
$smtpServer = $smtpServer
#Creating a Mail object
$msg = new-object Net.Mail.MailMessage
#Creating SMTP server object
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
#Email structure
$msg.From = $EmailFrom
$msg.ReplyTo = $EmailFrom
$msg.subject = $EmailSubject
$msg.body = $EmailBody
#Sending email

PowerShell Cmdlet

$email = @{
    To = $EmailTo
    From = $EmailFrom
    Subject = $EmailSubject
    Body = $EmailBody
    SMTPServer = $smtpServer
Send-MailMessage @Email

No comments:

Post a Comment