Share via


Powershell $msg.To ".To" is a ReadOnly property.

Question

Thursday, April 19, 2018 6:14 PM

param ([switch]$configure)
sp C:\Users\me\Documents\temp_txt.ps1 IsReadOnly false
$Date = Get-Date
$Server = gc env:computername
$Subject = "Hardware Alert from $Server $Date"
$SMTPServer = "smtp.office365.com"
$SMTPPort = '587'
$SMTPUser = '[email protected]'
$SMTPPassword = 'hunter2

# Create e-mail message
$msg = new-object Net.Mail.MailMessage

# Set e-mail properties
$msg.subject = $Subject

# Set e-mail body
$msg.body = $Body

# Creating SMTP server object
$SMTP = new-object Net.Mail.SmtpClient($SMTPServer)

# Email structure 
$msg.From = "[email protected]"
$msg.To = "[email protected]"

Attempting to run this script gives me ".To" is a ReadOnly property. I am not entirely sure what to do about this. 

All replies (3)

Thursday, April 19, 2018 6:59 PM

Because MailMessage.To property has ‘get’, but no ‘set’, it is really read-only: https://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.to%28v=vs.110%29.aspx. And it is not a string.

I think that you should create and add MailAddress objects. See an example in PowerShell: https://social.technet.microsoft.com/Forums/scriptcenter/en-US/bd3e9636-f258-416b-a3e4-ab70706bbdd7

See also: Send-MailMessage (/en-us/powershell/module/microsoft.powershell.utility/send-mailmessage?view=powershell-5.1


Monday, April 23, 2018 4:42 AM

Hi rb17460,

Thank you for posting here.

According to your question is more related to PowerShell, I will move it to Windows PowerShell forum for suitable support.

The CLR Forum discuss and ask questions about .NET Framework Base Classes (BCL) such as Collections, I/O, Regigistry, Globalization, Reflection. Also discuss all the other Microsoft libraries that are built on or extend the .NET Framework, including Managed Extensibility Framework (MEF), Charting Controls, CardSpace, Windows Identity Foundation (WIF), Point of Sale (POS), Transactions.

Best Regards,

Wendy

MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact [email protected].


Monday, April 23, 2018 5:16 AM

To send mail with PowerShell we use "Send-MailMessage".

help Send-MailMessage -online

Read the examples carefully.

\(ツ)_/