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.To.Add($EmailTo)
$msg.subject = $EmailSubject
$msg.attachments.add($Attachment)
$msg.body = $EmailBody
#Sending email
$smtp.Send($msg)
 

PowerShell Cmdlet

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

No comments:

Post a Comment