Sending email using PowerShell

Use the following code to send email using PowerShell

#Send Email
$msg = $null
$smtpServer = "0.0.0.0" 
$msg = new-object Net.Mail.MailMessage 
#$att = new-object Net.Mail.Attachment($file) 
$smtp = new-object Net.Mail.SmtpClient($smtpServer) 
$msg.From = "sender@domain.com" 
$msg.To.Add("recip1@domain.com") 
#$msg.To.Add("recip2@domain.com")
$msg.Subject = "Send To Report for $subjectdate" 
$msg.IsBodyHTML = $true 
$msg.Body = $html 
#$msg.Attachments.Add($att) 
$smtp.Send($msg)

If you do not have your own SMTP server you can use SMTP Server from gmail. Use the following code to use the gmail server

$EmailFrom = "notifications@somedomain.com"
$EmailTo = "me@earth.com" 
$Subject = "Notification from XYZ" 
$Body = "this is a notification from XYZ Notifications.." 
$SMTPServer = "smtp.gmail.com" 
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
$SMTPClient.EnableSsl = $true 
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("username", "password"); 
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)

If you need to send email to more than one person, use the comma, not semi colon to add more recipients.

Advertisements

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