一尘不染

为什么在发送SMTP电子邮件时出现“无法分配属性”的信息?

c#

我不明白为什么这段代码无法正常工作。我收到一条错误消息,指出无法分配属性

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 = "user@hotmail.com"; // <-- this one
mail.From = "you@yourcompany.com";
mail.Subject = "this is a test email.";
mail.Body = "this is my test email body";
client.Send(mail);

阅读 274

收藏
2020-05-19

共1个答案

一尘不染

mail.To并且mail.From是只读的。将它们移至构造函数。

using System.Net.Mail;

...

MailMessage mail = new MailMessage("you@yourcompany.com", "user@hotmail.com");
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);
2020-05-19