问题
We have an Asp.Net solution that's been in production for over 2 years using System.Net.Mail.MailMessage with the empty constructor:
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;
Yesterday we had a live site report the exception: The specified string is not in the required form for an email address. We fixed it by adding the required node to the web.config file.
The question is: Why did this ever work? or Could it have ever worked?
Error: The specified string is not in the form required for an e-mail address. at System.Net.Mail.MailAddressParser.ReadCfwsAndThrowIfIncomplete(String data, Int32 index) at System.Net.Mail.MailAddressParser.ParseDomain(String data, Int32& index) at System.Net.Mail.MailAddressParser.ParseAddress(String data, Boolean expectMultipleAddresses, Int32& index) at System.Net.Mail.MailAddressParser.ParseAddress(String data) at System.Net.Mail.MailAddress..ctor(String address, String displayName, Encoding displayNameEncoding) at System.Net.Mail.MailMessage..ctor()
Thanks
EDITS:
- We updated from .net 3.5 to 4.0 last month!
- Added stack trace
- After 7 months, the error only occurs on some servers. Why?
回答1:
You need to set the from
in your Web.Config if you are using SMTP settings from Web.Config. Check this MSDN Link for more details.
<mailSettings>
<smtp from="xxxxx@gmail.com"> <!-- This is important when constructing a
new mail message. Make sure 'from' is
an email address. -->
<network host="smtp.gmail.com" password="yourpassword"
userName="xxxxx@gmail.com" port="587" />
</smtp>
</mailSettings>
If you are not using SMTPCLIENT
from Web.Config then completely remove the from
attribute from Web.Config and construct your own SmtpClient
in code like this:
var fromAddress = new MailAddress("xxxxxx@gmail.com", "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
};
回答2:
Is your code set some properties after this using statement?
The default constructor has and still does work, as long as you set the properties necessary later in the code before actually triggering the send. The web.config node, typically just provides default values for those properties.
I would look into it and see if some of the properties are not getting set right and why.
来源:https://stackoverflow.com/questions/16108105/when-does-the-empty-mailmessage-constructor-work