SmtpClient从Windows应用程序发送邮件但在ASP.NET / MVC中失败

时间:2016-05-10 06:46:50

标签: c# asp.net asp.net-mvc smtp smtpclient

嗨,我收到了一个有趣的错误。我可以发送电子邮件,如果我使用Windows应用程序,但相同的代码作为ASP.NET / MVC应用程序的一部分运行时抛出SendMessage错误说 - System.Net.Mail.SmtpException: Failure sending mail. ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions

我使用的代码是:

 using (MailMessage message = new MailMessage("from@my.com", "t0@my.com"))
                {
                    message.CC.Add("cc@my.com");
                    message.IsBodyHtml = true;
                    message.Subject = "Test subject");
                    message.Body = "Test Body";
                    SmtpClient client = new SmtpClient();
                    client.Host = "abc.com";
                    client.Port = 25;
                    client.Send(message);
                }

有人可以在这里提出错误的建议。

谢谢, 甲

1 个答案:

答案 0 :(得分:0)

  

获取或设置用于SMTP事务的主机的名称或IP地址。

msdn说。也许你不能用“abc.com”作为主持人。

对于gmail可能应该是

client.Host = "smtp.gmail.com";

它对我有用

using (MailMessage message = new MailMessage("from@my.com", "t0@my.com"))
{
    message.CC.Add("cc@my.com");
    message.IsBodyHtml = true;
    message.Subject = "Test subject";
    message.Body = "Test Body";
    SmtpClient client = new SmtpClient();
    client.Host = "smtp.gmail.com";
    client.Port = 25;
    client.Credentials = new NetworkCredential("yourEmail", "Password");
    client.EnableSsl = true;
    client.UseDefaultCredentials = false;
    client.Send(message);
}