System.Net.Mail不发送生产

时间:2021-08-28 18:14:00

I am trying to implement a "forgot password" method into my site. It works perfectly in debug. Using the same code and db, but published to our web server it fails when it tries to send the message.

我正在尝试在我的网站中实施“忘记密码”方法。它在调试中完美运行。使用相同的代码和数据库,但发布到我们的Web服务器时,它在尝试发送消息时失败。

The error that I get is:

我得到的错误是:

There was an error sending you an email.
The specified string is not in the form required for an e-mail address.

The email is valid, so I have no idea why it is failing.

电子邮件是有效的,所以我不知道为什么它失败了。

Because it is a live environment I cannot step through the code to see exactly where and why it is failing. I implemented db logging so I can see how far it gets before it fails and it successfully executes all code up to this point:

因为它是一个实时环境,所以我无法单步执行代码以确切地了解它失败的原因和原因。我实现了数据库日志记录,因此我可以看到它在失败之前获得了多远,并且到目前为止它成功执行了所有代码:

 var smtp = new SmtpClient
 {
     Host = host,
     Port = port,
     EnableSsl = ssl,
     DeliveryMethod = SmtpDeliveryMethod.Network,
     UseDefaultCredentials = false,
     Credentials = new NetworkCredential(fromAddress.Address, fromPw)
 };
 using (var message = new MailMessage()
 {
     Subject = subject,
     Body = body,
     IsBodyHtml = ishtml,
     From = fromAddress
 })

 {
     foreach (MailAddress t in toCol)
     { message.To.Add(t); }
     foreach (MailAddress c in ccCol)
     { message.CC.Add(c); }
     foreach (MailAddress b in bccCol)
     { message.Bcc.Add(b); }
     smtp.Send(message);
 }

It never gets to the next db logging so it has to be failing here. In my test I have exactly one email address for the to and none for bcc and cc. When stepping through in debug it correctly loads the single email address and doesn't load any for cc and bcc. I have no idea what it is considering to be an invalid email address.

它永远不会进入下一个db日志记录,所以它必须在这里失败。在我的测试中,我只有一个电子邮件地址为to,没有bcc和cc。在调试中单步执行时,它会正确加载单个电子邮件地址,并且不会为cc和bcc加载任何内容。我不知道它是一个无效的电子邮件地址。

EDIT:

We use Google Apps as our mail server so both my workstation and the server have to connect. I am using the following:

我们使用Google Apps作为邮件服务器,因此我的工作站和服务器都必须连接。我使用以下内容:

  • Host: smtp.gmail.com
  • Port: 587
  • EnableSsl: true
  • Credentials: valid username and password that work in debug
  • 凭据:在调试中有效的有效用户名和密码

EDIT 2: To incorporate some of the suggestions from you.
The fromAddress is set earlier using values from the db like this:

编辑2:结合你的一些建议。使用db中的值来设置fromAddress,如下所示:

DataTable ts = DAL.Notification.GetNotificationSettings();
var fromEmail = ts.Rows[0]["fromadr"].ToString().Trim();
var fromName = ts.Rows[0]["fromname"].ToString().Trim();
var host = ts.Rows[0]["server"].ToString().Trim();
var port = Convert.ToInt32(ts.Rows[0]["smtpport"]);
var ssl = Convert.ToBoolean(ts.Rows[0]["is_ssl"]);
var ishtml = Convert.ToBoolean(ts.Rows[0]["is_html"]);
var bodyTemplate = ts.Rows[0]["bodyTemplate"].ToString();
body = bodyTemplate.Replace("{CONTENT}", body).Replace("{emailFooter}","");// Needs to use the Global emailFooter resource string

var fromAddress = new MailAddress(fromEmail, fromName);

I have even tried hard coding the from address like this:

我甚至尝试过这样的来自地址的硬编码:

message.From = new MailAddress("websystem@mydomain.com");

I still get the error and it still fails when defining the message.

我仍然收到错误,但在定义消息时仍然失败。

Any other suggestions on how to find and fix the problem?

有关如何查找和解决问题的任何其他建议?

ANSWER

I did not define the default from address in the web.config like this:

我没有在web.config中定义默认的地址,如下所示:

    <system.net>
     <mailSettings>
       <smtp from="email@yourdomain.com">
         <network host="smtp.yourdomain.com"/>
       </smtp>
     </mailSettings>   </system.net>

So it failed at var message = new MailMessage() before I could define the correct from address.

因此,在我可以定义正确的发件人地址之前,它在var message = new MailMessage()时失败了。

I either needed to implement var message = new MailMessage(From,To) or provide a default from address in web.config (which is what I did)

我要么需要实现var message = new MailMessage(From,To),要么在web.config中提供地址的默认值(这就是我所做的)

2 个解决方案

#1


4  

This error can be caused by two things:

此错误可能由两件事引起:

  1. One of the email addresses your using (for message.To, message.CC or message.Bcc) is invalid, i.e. it doesn't follow the required format of someuser@somedomain.xxx.

    您使用的电子邮件地址之一(对于message.To,message.CC或message.Bcc)无效,即它不符合someuser@somedomain.xxx所需的格式。

  2. The From address configured in Web.Config is invalid:

    Web.Config中配置的发件人地址无效:

    <system.net>
      <mailSettings>
        <smtp from="invalid@@email">
          <network host="smtp.gmail.com"/>
        </smtp>
      </mailSettings>
    </system.net>
    

#2


1  

My recommendation is to use try/catch statements to further narrow the problem. I'd also temporarily lose the using statement for the MailMessage for easier troubleshooting.

我的建议是使用try / catch语句来进一步缩小问题范围。我还会暂时丢失MailMessage的using语句,以便更轻松地进行故障排除。

Example:

var smtp;
try
{
    smtp = new SmtpClient
    {
        Host = host,
        Port = port,
        EnableSsl = ssl,
        DeliveryMethod = SmtpDeliveryMethod.Network,
        UseDefaultCredentials = false,
        Credentials = new NetworkCredential(fromAddress.Address, fromPw)
    };
}
catch (Exception exc)
{
    MessageBox.Show("Error creating SMTP client: " + exc.Message);
}

var message = new MailMessage();
try
{
    message.Subject = subject;
    message.Body = body;
    message.IsBodyHtml = ishtml;
    message.From = fromAddress;
}
catch (Exception exc)
{
    MessageBox.Show("Error creating MailMessage: " + exc.Message);
}


try
{
    foreach (MailAddress t in toCol)
        message.To.Add(t);
}
catch (Exception exc)
{
    MessageBox.Show("Error adding TO addresses: " + exc.Message);
}

try
{
    foreach (MailAddress c in ccCol)
        message.CC.Add(c);
}
catch (Exception exc)
{
    MessageBox.Show("Error adding CC addresses: " + exc.Message);
}

try
{
    foreach (MailAddress b in bccCol)
        message.Bcc.Add(b);
}
catch (Exception exc)
{
    MessageBox.Show("Error adding BCC addresses: " + exc.Message);
}

try
{
    smtp.Send(message);
}
catch (Exception exc)
{
    MessageBox.Show("Error sending message: " + exc.Message);
}

Alternatively, you could replace the various MessageBox.Show() statements with something that writes to a log file. By breaking this up you should be able to pinpoint the problem with more accuracy.

或者,您可以使用写入日志文件的内容替换各种MessageBox.Show()语句。通过打破这一点,您应该能够更准确地查明问题。

#1


4  

This error can be caused by two things:

此错误可能由两件事引起:

  1. One of the email addresses your using (for message.To, message.CC or message.Bcc) is invalid, i.e. it doesn't follow the required format of someuser@somedomain.xxx.

    您使用的电子邮件地址之一(对于message.To,message.CC或message.Bcc)无效,即它不符合someuser@somedomain.xxx所需的格式。

  2. The From address configured in Web.Config is invalid:

    Web.Config中配置的发件人地址无效:

    <system.net>
      <mailSettings>
        <smtp from="invalid@@email">
          <network host="smtp.gmail.com"/>
        </smtp>
      </mailSettings>
    </system.net>
    

#2


1  

My recommendation is to use try/catch statements to further narrow the problem. I'd also temporarily lose the using statement for the MailMessage for easier troubleshooting.

我的建议是使用try / catch语句来进一步缩小问题范围。我还会暂时丢失MailMessage的using语句,以便更轻松地进行故障排除。

Example:

var smtp;
try
{
    smtp = new SmtpClient
    {
        Host = host,
        Port = port,
        EnableSsl = ssl,
        DeliveryMethod = SmtpDeliveryMethod.Network,
        UseDefaultCredentials = false,
        Credentials = new NetworkCredential(fromAddress.Address, fromPw)
    };
}
catch (Exception exc)
{
    MessageBox.Show("Error creating SMTP client: " + exc.Message);
}

var message = new MailMessage();
try
{
    message.Subject = subject;
    message.Body = body;
    message.IsBodyHtml = ishtml;
    message.From = fromAddress;
}
catch (Exception exc)
{
    MessageBox.Show("Error creating MailMessage: " + exc.Message);
}


try
{
    foreach (MailAddress t in toCol)
        message.To.Add(t);
}
catch (Exception exc)
{
    MessageBox.Show("Error adding TO addresses: " + exc.Message);
}

try
{
    foreach (MailAddress c in ccCol)
        message.CC.Add(c);
}
catch (Exception exc)
{
    MessageBox.Show("Error adding CC addresses: " + exc.Message);
}

try
{
    foreach (MailAddress b in bccCol)
        message.Bcc.Add(b);
}
catch (Exception exc)
{
    MessageBox.Show("Error adding BCC addresses: " + exc.Message);
}

try
{
    smtp.Send(message);
}
catch (Exception exc)
{
    MessageBox.Show("Error sending message: " + exc.Message);
}

Alternatively, you could replace the various MessageBox.Show() statements with something that writes to a log file. By breaking this up you should be able to pinpoint the problem with more accuracy.

或者,您可以使用写入日志文件的内容替换各种MessageBox.Show()语句。通过打破这一点,您应该能够更准确地查明问题。