我不明白为什么这个代码不能工作。我得到一个错误,说属性不能被分配

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.example";
mail.Subject = "this is a test email.";
mail.Body = "this is my test email body";
client.Send(mail);

当前回答

这样的:

mail.To = "user@hotmail.com";

应该是:

mail.To.Add(new MailAddress("user@hotmail.com"));

其他回答

smtp.Host = "smtp.gmail.com"; // the host name
smtp.Port = 587; //port number
smtp.EnableSsl = true; //whether your smtp server requires SSL
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;

阅读这篇文章了解更多细节

如果你想让你的电子邮件和密码不出现在你的代码,并希望你的公司电子邮件客户端服务器使用你的windows凭据使用下面。

client.Credentials = CredentialCache.DefaultNetworkCredentials;

public static void SendMail(MailMessage Message)
{
    SmtpClient client = new SmtpClient();
    client.Host = "smtp.googlemail.com";
    client.Port = 587;
    client.UseDefaultCredentials = false;
    client.DeliveryMethod = SmtpDeliveryMethod.Network;
    client.EnableSsl = true;
    client.Credentials = new NetworkCredential("myemail@gmail.com", "password");
    client.Send(Message); 
}

终于开始工作了:)

using System.Net.Mail;
using System.Text;

...

// Command line argument must the the SMTP host.
SmtpClient client = new SmtpClient();
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("user@gmail.com","password");

MailMessage mm = new MailMessage("donotreply@domain.example", "sendtomyemail@domain.example", "test", "test");
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

client.Send(mm);

抱歉之前拼写不太好

邮件。寄和寄。From是只读的。将它们移动到构造函数中。

using System.Net.Mail;

...

MailMessage mail = new MailMessage("you@yourcompany.example", "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);