客户端未经过身份验证

时间:2015-09-22 01:54:06

标签: asp.net email iis

发布我的应用程序并将其部署到IIS后,我遇到了一种错误,表示客户端未经过身份验证。

在我的web.config中,我有这行代码来设置smtp邮件服务器。

 <system.net>
<mailSettings>
  <smtp>
    <network host="ap.smtp.lear.com" port="25" />
  </smtp>
</mailSettings>

在我的控制器中:

  public void Send(string[] to = null, string[] cc = null, string body = null)
    {
        MailMessage message = new MailMessage();
        message.From = new MailAddress("myapp@samp.com");

        //for to emails, since it is in array form, it will called individually by using foreach loop

        foreach (var em in to) {
            message.To.Add(new MailAddress(em));
        }

        foreach (var ccem in cc)
        {
            message.CC.Add(new MailAddress(ccem));
        }

        message.Subject = "Employee Regularization - For Approval";
        message.IsBodyHtml = true;
        message.Body = body;
        SmtpClient client = new SmtpClient();
        client.Send(message);
        message.Dispose();
        client.Dispose();
    }

我正在服务器中部署我的应用程序,该服务器还托管了可以发送电子邮件的其他应用程序。有什么不对或错过了什么吗?

1 个答案:

答案 0 :(得分:0)

你说:

client.Credentials = new System.Net.NetworkCredential();

但您没有提供用户名和密码。也许你应该改变你使用的the overload

client.Credentials = new System.Net.NetworkCredential("username", "password");

此外,当您使用IDisposable内容时,即使出现错误,也需要确保对象处理。稍后在代码中简单地调用.Dispose()就不够好了。如果在声明对象和处理对象之间发生了某些错误,则无法访问.Dispose()。有两种方法可以做到这一点。您可以尝试/ catch / finally并在finally块中调用.Dispose()。或者您可以使用using语句。我选择了后者。

public void Send(string[] to = null, string[] cc = null, string body = null)
{
    using (MailMessage message = new MailMessage())
    {
        message.From = new MailAddress("myapp@samp.com");

        foreach (var em in to)
        {
            message.To.Add(new MailAddress(em));
        }

        foreach (var ccem in cc)
        {
            message.CC.Add(new MailAddress(ccem));
        }

        message.Subject = "Employee Regularization - For Approval";
        message.IsBodyHtml = true;
        message.Body = body;
        using(SmtpClient client = new SmtpClient())
        {
            client.Credentials = new System.Net.NetworkCredential("username", "password");
            client.UseDefaultCredentials = false;
            client.Send(message);
        }
    }
}