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)

4
Leave a Reply

avatar
2 Comment threads
2 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
4 Comment authors
MaximusMonkMax HasenoehrlBrandon LawsonAlaysha_7 Recent comment authors

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
newest oldest
Notify of
Alaysha_7
Guest
Alaysha_7

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.

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”

MaximusMonk
Guest
MaximusMonk

Set UseDefaultCredentials = $true

Max Hasenoehrl
Guest
Max Hasenoehrl

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?