为啥我在发送 SMTP 电子邮件时收到“'property cannot be assigned”?
Posted
技术标签:
【中文标题】为啥我在发送 SMTP 电子邮件时收到“\'property cannot be assigned”?【英文标题】:Why do I get "'property cannot be assigned" when sending an SMTP email?为什么我在发送 SMTP 电子邮件时收到“'property cannot be assigned”? 【发布时间】:2012-03-01 08:32:07 【问题描述】:我不明白为什么这段代码不起作用。我收到一条错误消息,提示无法分配属性
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);
【问题讨论】:
Nore 如果您尝试通过 SMTP 通过 gmail 发送,您需要允许不太安全的应用程序访问您的帐户 support.google.com/accounts/answer/6010255?hl=en 【参考方案1】:这个:
mail.To = "user@hotmail.com";
应该是:
mail.To.Add(new MailAddress("user@hotmail.com"));
【讨论】:
使用这个和默认的MailMessage
构造函数允许你设置To
字段而不设置From
,这将默认为<smtp> Element (Network Settings)中的值
谁能告诉我怎样才能使它适用于我自己的 SMTP 服务器而不是 Google SMTP?我在尝试连接到我的 SMTP 服务器时收到"Unable to connect to the remote server" "The requested address is not valid in its context IP-ADDRESS:25"
error
@YuDroid 正确设置SmtpClient
的Host
和Port
属性。
@Mithrandir 是的,我设置正确。我已经在 Outlook 中设置了我的 SMTP 邮件帐户,并从他们那里获取了所有必要的设置。主机和端口在 Web.config 文件中声明,我正在运行时获取它。【参考方案2】:
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);
【讨论】:
mail.To 是只读的,from 不是。公共 MailAddressCollection 到 get; 那是因为它是一个集合。你可以调用添加到它 @Oskar 好的,所以我应该更具体一些。您不能将 mail.to 设置为特定地址。您必须使用构造函数或调用 add。我只是在解决第一个编译器警告:错误 CS0200:无法将属性或索引器“System.Net.Mail.MailMessage.To”分配给——它是只读的 @DougHauf 您可以将 SmtpClient 类与受密码保护的 smtp 服务器一起使用。您的 smtp 服务器似乎是一个内部服务器,这意味着您的程序只能在网络上连接到该 smtp 服务器。client.Host = "mail.youroutgoingsmtpserver.com";
client.Credentials = new System.Net.NetworkCredential("yourusername", "yourpassword");
SmtpClient 实现了 IDisposable,因此您应该将其更改为: using (SmtpClient client = new SmtpClient()) ... 【参考方案3】:
终于开始工作了:)
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.com", "sendtomyemail@domain.co.uk", "test", "test");
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
client.Send(mm);
抱歉之前的拼写不好
【讨论】:
不应该有 mm.Dispose() 吗? 顺便说一句,默认的 smtp 端口是 25。 谢谢!直到今天它仍然有效,但使用的是 Outlook。 [client.Host = "smtp-mail.outlook.com";] 587 是安全的 smtp。 @freej17 添加 MailAddress 副本 = new MailAddress("Notification_List@contoso.com"); mm.CC.Add(复制);【参考方案4】: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);
【讨论】:
这根本没有解决为什么 OP 不能分配给MailMessage
属性。【参考方案5】:
这就是我的工作方式。希望对你有用
MailMessage objeto_mail = new MailMessage();
SmtpClient client = new SmtpClient();
client.Port = 25;
client.Host = "smtp.internal.mycompany.com";
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("user", "Password");
objeto_mail.From = new MailAddress("from@server.com");
objeto_mail.To.Add(new MailAddress("to@server.com"));
objeto_mail.Subject = "Password Recover";
objeto_mail.Body = "Message";
client.Send(objeto_mail);
【讨论】:
【参考方案6】: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;
通过this article了解更多详情
【讨论】:
【参考方案7】:如果您不想让您的电子邮件和密码出现在您的代码中,并希望您的公司电子邮件客户端服务器使用您的 Windows 凭据,请使用下面的说明。
client.Credentials = CredentialCache.DefaultNetworkCredentials;
Source
【讨论】:
这与client.UseDefaultCredentials = true;相同;虽然【参考方案8】:使用发件人和收件人的电子邮件地址初始化MailMessage
。它应该类似于
string from = "codeforwin@gmail.com"; //Senders email
string to = "reciever@gmail.com"; //Receiver's email
MailMessage msg = new MailMessage(from, to);
阅读how to send emails in c#的完整代码sn-p
【讨论】:
【参考方案9】:这也可以..
string your_id = "your_id@gmail.com";
string your_password = "password";
try
SmtpClient client = new SmtpClient
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new System.Net.NetworkCredential(your_id, your_password),
Timeout = 10000,
;
MailMessage mm = new MailMessage(your_iD, "recepient@gmail.com", "subject", "body");
client.Send(mm);
Console.WriteLine("Email Sent");
catch (Exception e)
Console.WriteLine("Could not end email\n\n"+e.ToString());
【讨论】:
【参考方案10】:MailMessage mm = new MailMessage(txtEmail.Text, txtTo.Text);
mm.Subject = txtSubject.Text;
mm.Body = txtBody.Text;
if (fuAttachment.HasFile)//file upload select or not
string FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
mm.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream, FileName));
mm.IsBodyhtml = false;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential(txtEmail.Text, txtPassword.Text);
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
Response.write("Send Mail");
观看视频: https://www.youtube.com/watch?v=bUUNv-19QAI
【讨论】:
虽然此视频可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接的答案可能会失效 msdn 为 UseDefaultCredentials 属性声明 "如果 UseDefaultCredentials 属性设置为 false,则在连接到服务器时,Credentials 属性中设置的值将用于凭据。 ",因此如果您使用了 Credentials 属性(自定义凭据),则应将 UseDefaultCredentials 属性设置为 false。【参考方案11】: //Hope you find it useful, it contain too many things
string smtpAddress = "smtp.xyz.com";
int portNumber = 587;
bool enableSSL = true;
string m_userName = "support@xyz.com";
string m_UserpassWord = "56436578";
public void SendEmail(Customer _customers)
string emailID = gghdgfh@gmail.com;
string userName = DemoUser;
string emailFrom = "qwerty@gmail.com";
string password = "qwerty";
string emailTo = emailID;
// Here you can put subject of the mail
string subject = "Registration";
// Body of the mail
string body = "<div style='border: medium solid grey; width: 500px; height: 266px;font-family: arial,sans-serif; font-size: 17px;'>";
body += "<h3 style='background-color: blueviolet; margin-top:0px;'>Aspen Reporting Tool</h3>";
body += "<br />";
body += "Dear " + userName + ",";
body += "<br />";
body += "<p>";
body += "Thank you for registering </p>";
body += "<p><a href='"+ sURL +"'>Click Here</a>To finalize the registration process</p>";
body += " <br />";
body += "Thanks,";
body += "<br />";
body += "<b>The Team</b>";
body += "</div>";
// this is done using using System.Net.Mail; & using System.Net;
using (MailMessage mail = new MailMessage())
mail.From = new MailAddress(emailFrom);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
// Can set to false, if you are sending pure text.
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
smtp.Credentials = new NetworkCredential(emailFrom, password);
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
【讨论】:
请考虑使用您的答案来解释解决方案以及为什么原始提问者遇到问题,而不是简单地发布代码墙。这对于最初的提问者和未来的访问者都将更有用,以了解问题发生的原因。 @RedBassett 感谢您的建议。我刚刚编辑并把一些信息放在了 cmets 中,下次我记住你所说的任何内容。【参考方案12】:只需要试试这个:
string smtpAddress = "smtp.gmail.com";
int portNumber = 587;
bool enableSSL = true;
string emailFrom = "companyemail";
string password = "password";
string emailTo = "Your email";
string subject = "Hello!";
string body = "Hello, Mr.";
MailMessage mail = new MailMessage();
mail.From = new MailAddress(emailFrom);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
smtp.Credentials = new NetworkCredential(emailFrom, password);
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
【讨论】:
【参考方案13】:首先转到https://myaccount.google.com/lesssecureapps 并设置允许不太安全的应用true。
然后使用下面的代码。仅当您的发件人电子邮件地址来自 gmail 时,以下代码才有效。
static void SendEmail()
string mailBodyhtml =
"<p>some text here</p>";
var msg = new MailMessage("from@gmail.com", "to1@gmail.com", "Hello", mailBodyhtml);
msg.To.Add("to2@gmail.com");
msg.IsBodyHtml = true;
var smtpClient = new SmtpClient("smtp.gmail.com", 587); //**if your from email address is "from@hotmail.com" then host should be "smtp.hotmail.com"**
smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = new NetworkCredential("from@gmail.com", "password");
smtpClient.EnableSsl = true;
smtpClient.Send(msg);
Console.WriteLine("Email Sent Successfully");
【讨论】:
【参考方案14】:截至 2017 年 3 月,这对我有用。 从上面的“终于开始工作:)”的解决方案开始,起初没有用。
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("<me>@gmail.com", "<my pw>");
MailMessage mm = new MailMessage(from_addr_text, to_addr_text, msg_subject, msg_body);
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
client.Send(mm);
【讨论】:
【参考方案15】:MailKit 是一个开源跨平台 .NET 邮件客户端库,它基于 MimeKit 并针对移动设备进行了优化。 它具有比 System.Net.Mail 更好的更多高级功能 通过 MimeKit 支持 Microsoft TNEF。
从here下载nuget包。
看这个例子就可以发邮件了
MimeMessage mailMessage = new MimeMessage();
mailMessage.From.Add(new MailboxAddress(senderName, sender@address.com));
mailMessage.Sender = new MailboxAddress(senderName, sender@address.com);
mailMessage.To.Add(new MailboxAddress(emailid, emailid));
mailMessage.Subject = subject;
mailMessage.ReplyTo.Add(new MailboxAddress(replyToAddress));
mailMessage.Subject = subject;
var builder = new BodyBuilder();
builder.TextBody = "Hello There";
try
using (var smtpClient = new SmtpClient())
smtpClient.Connect("HostName", "Port", MailKit.Security.SecureSocketOptions.None);
smtpClient.Authenticate("user@name.com", "password");
smtpClient.Send(mailMessage);
Console.WriteLine("Success");
catch (SmtpCommandException ex)
Console.WriteLine(ex.ToString());
catch (Exception ex)
Console.WriteLine(ex.ToString());
【讨论】:
【参考方案16】:这个答案的特点:
尽可能使用“使用”(IDisposable 接口) 使用Object initializers Async Programming 将 SmtpConfig 提取到外部类(根据需要进行调整)这是提取的代码:
public async Task SendAsync(string subject, string body, string to)
using (var message = new MailMessage(smtpConfig.FromAddress, to)
Subject = subject,
Body = body,
IsBodyHtml = true
)
using (var client = new SmtpClient()
Port = smtpConfig.Port,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Host = smtpConfig.Host,
Credentials = new NetworkCredential(smtpConfig.User, smtpConfig.Password),
)
await client.SendMailAsync(message);
类 SmtpConfig:
public class SmtpConfig
public string Host get; set;
public string User get; set;
public string Password get; set;
public int Port get; set;
public string FromAddress get; set;
【讨论】:
【参考方案17】:通过 smtp 发送电子邮件
public void EmailSend(string subject, string host, string from, string to, string body, int port, string username, string password, bool enableSsl)
try
MailMessage mail = new MailMessage();
SmtpClient smtpServer = new SmtpClient(host);
mail.Subject = subject;
mail.From = new MailAddress(from);
mail.To.Add(to);
mail.Body = body;
smtpServer.Port = port;
smtpServer.Credentials = new NetworkCredential(username, password);
smtpServer.EnableSsl = enableSsl;
smtpServer.Send(mail);
catch (Exception ex)
throw new Exception(ex.Message);
【讨论】:
以上是关于为啥我在发送 SMTP 电子邮件时收到“'property cannot be assigned”?的主要内容,如果未能解决你的问题,请参考以下文章
Python邮件发送。为啥我用smtp发送邮件,发送成功没有报错,却没有收到邮件?求解
smtp 发送电子邮件,为啥一个附件可以有两个 Content-Type?