发送邮件时无法连接到远程服务器c#

时间:2013-08-05 14:20:43

标签: c# .net email io html-email

我目前正在尝试通过System.Net.Mail.MailMessage发送电子邮件,但是当我运行我的代码时,我生成此异常,发送邮件失败。内部异常是:无法连接到远程服务器。我相信我正在连接到远程服务器,但我很好奇为什么我得到这个例外 以下是我的代码的外观:

 try
        {
            System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();

            msg.Subject = "Testing Email";

            msg.From = new System.Net.Mail.MailAddress("test@gmail.com");

            msg.To.Add(new System.Net.Mail.MailAddress("isavepluscom@gmail.com"));

            msg.Body = "testing the email";



            System.Net.Mail.SmtpClient smpt = new System.Net.Mail.SmtpClient();

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

            smpt.Port = 587;

            smpt.EnableSsl = true;

            smpt.Credentials = new System.Net.NetworkCredential("test@gmail.com", "1234567890");

            smpt.Send(msg);
        }
        catch (Exception ex)
        {

        }

即使我在代码中设置凭据,我是否需要在webconfig文件中包含任何内容?

2 个答案:

答案 0 :(得分:3)

您可以尝试将代码缩短为类似以下内容

 var smptClient = new SmtpClient("smtp.gmail.com", 587)
 {
     Credentials = new NetworkCredential("isavepluscom@gmail.com", "123456789"),
     EnableSsl = true
 };
  smptClient.Send("isavepluscom@gmail.com", "test@gmail.com", "Testing Email", "testing the email");

答案 1 :(得分:0)

看起来像一个安全例外。确保端口587已打开进行通信,如果是服务器,我将默认阻止。