Send email with PowerShell

Ever want to send an email with PowerShell?  Well now you can! Simply add the code below to the end of a PowerShell script.  PowerShell will then use the Net.Mail.SmtpClient object to send the email. That’s it! Don’t forget to but in your appropriate information.

# Define and create the message
$strTo = "SendtoEmailAddress"
$strFrom = "FromEmailAddress"
$strSubject = "Email Subject"
$strBody = "Body of text for email"
$objMessage = New-Object System.Net.Mail.MailMessage –ArgumentList $strFrom, $strTo, $strSubject, $strBody

# Add an attachment
$strAttachment = "C:\Attachment\location"
$objAttachment = New-Object System.Net.Mail.Attachment –ArgumentList $strAttachment, "Application/Octet"
$objMessage.Attachments.Add($objAttachment)

# Define the SMTP server
$strSMTPServer = "smtp.server.com"
$objSMTP = New-Object System.Net.Mail.SMTPClient –ArgumentList $strSMTPServer

# Send the message
$objSMTP.Send($objMessage)

Leave a Reply

4 Comments on "Send email with PowerShell"

avatar
  Subscribe  
newest oldest
Notify of
Alaysha_7
Guest

Hello,

I run this command in Exchange server 2007 and below error is displayed when latest row is performed ($objSMTP.Send($objMessage))

Error:

Exception calling “Send” with “1” argument(s): “The SMTP server requires a secure connection or the client was not authenticated.
The server response was: 5.7.1 Client was not authenticated”

Anyone can help? I do not know what to do.

MaximusMonk
Guest

Set UseDefaultCredentials = $true

Brandon Lawson
Guest

Anonymous users do not have permission on the “Default receive connector.”

Click on Server configuration
Click on Hub Transport, select default receive connector and go to properties
Click on Permission group
Tick the check box where is says “Anonymous users”

Max Hasenoehrl
Guest

Hi Brandon! This script works like a charm. I have one question is regards to being able to CC I can’t find the command to carbon copy. Is this possible?