我们有一个使用了System.Net.Mail.MailMessage和空构造函数的Asp.Net解决方案已经投入生产超过2年了:
using (MailMessage _mailMessage = new MailMessage()) // Exception thrown here
{
_mailMessage.From = new MailAddress(sFrom); // Setting additional properties - never gets here
_mailMessage.Body = sBody;
_mailMessage.Subject = sSubject;
_mailMessage.IsBodyHtml = true;
昨天我们有一个实时站点报告例外:所指定的字符串不是电子邮件地址的必需格式。通过将所需的节点添加到web.config文件中,我们对其进行了修复。
问题是:为什么这行得通?还是曾经奏效?
错误:指定的字符串不是电子邮件地址所需的格式。在System.Net.Mail.MailAddressParser.ReadCfwsAndThrowIfIncomplete(字符串数据,Int32索引)在System.Net.Mail.MailAddressParser.ParseDomain(字符串数据,Int32&索引)在System.Net.Mail.MailAddressParser.ParseAddress(字符串数据,布尔ExpectMultipleAddresses,Int32&索引)在System.Net.Mail.MailAddressParser.ParseAddress(字符串数据)在System.Net.Mail.MailAddress..ctor处(字符串地址,字符串displayName,Encoding displayNameEncoding)在System.Net.Mail.MailMessage..ctor()
谢谢
编辑:
如果使用Web.Config中的SMTP设置,则需要在Web.Config中设置from
。检查此MSDN Link了解更多详细信息。
<mailSettings>
<smtp from="[email protected]"> <!-- This is important when constructing a
new mail message. Make sure 'from' is
an email address. -->
<network host="smtp.gmail.com" password="yourpassword"
userName="[email protected]" port="587" />
</smtp>
</mailSettings>
如果您不使用Web.Config中的SMTPCLIENT
,则从Web.Config中完全删除from
属性,并使用如下代码构建自己的SmtpClient
:
var fromAddress = new MailAddress("[email protected]", "Mr XXXXX");
string fromPassword = "yourpassword";
message.From = fromAddress;
var client = new SmtpClient()
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = false,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
Timeout = 20000
};
您的代码在使用using语句之后是否设置了某些属性?
默认构造函数具有并且仍然有效,只要您在稍后实际触发发送之前在代码中设置了必要的属性即可。 web.config节点通常仅提供这些属性的默认值。
我会调查一下,看看是否某些属性设置不正确以及原因。