Why do I get "'property cannot be assigned" when sending an SMTP email?

Sam Stephenson picture Sam Stephenson · Feb 8, 2012 · Viewed 724.1k times · Source

I can't understand why this code is not working. I get an error saying property can not be assigned

MailMessage mail = new MailMessage();
SmtpClient client = new SmtpClient();            
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "smtp.gmail.com";
mail.To = "[email protected]"; // <-- this one
mail.From = "[email protected]";
mail.Subject = "this is a test email.";
mail.Body = "this is my test email body";
client.Send(mail);

Answer

MRB picture MRB · Feb 8, 2012

mail.To and mail.From are readonly. Move them to the constructor.

using System.Net.Mail;

...

MailMessage mail = new MailMessage("[email protected]", "[email protected]");
SmtpClient client = new SmtpClient();
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "smtp.gmail.com";
mail.Subject = "this is a test email.";
mail.Body = "this is my test email body";
client.Send(mail);