Smtp异常无法发送邮件

时间:2015-09-04 06:54:17

标签: c# wpf smtpclient

System.Net.Mail.SmtpException: 
Failure sending mail. ---> 
System.Net.WebException: 
Unable to connect to the remote server ---> 
System.Net.Sockets.SocketException: 
No connection could be made because the target machine actively refused it xx.x.xx.xxx:25

我的 SMTP 主机位于IP地址之上我无法收到邮件,因为它引发了上述异常。

下面是我的代码

mail.From = new MailAddress(email.From.EmailAddress,email.From.FullName);
mail.Subject = email.Subject;
mail.Body = email.Body;
if (email.Body.Contains("<html>"))
{
    mail.IsBodyHtml = true;
}
if (!email.ExcludeAttachment && !string.IsNullOrEmpty(email.AttachmentPath))
    mail.Attachments.Add(new Attachment(email.AttachmentPath));

client = new SmtpClient();
client.Host = ConfigurationSettings.AppSettings["SmtpServer"].ToString();
client.Send(mail);

1 个答案:

答案 0 :(得分:0)

您获得此功能的最可能原因是您需要对服务器进行身份验证。您可能还需要通过身份验证发送,查看我的工作代码,看看您是否可以调整它以满足您的需求。

也许值得抓住Telrik Fiddler看看smtp服务器的响应是什么

var client = new SmtpClient
        {
            Host = txtOutGoingServer.Text,
            Port = Convert.ToInt16(txtServerPort.Text),
            EnableSsl = true,
            DeliveryMethod = SmtpDeliveryMethod.Network,
            Credentials = new NetworkCredential(txtUserName.Text, txtPassword.Password),
            Timeout = 20000
        };

 try
       {
           m.To.Add(new MailAddress(dr[0].ToString().Trim()));
           m.From = new MailAddress(txtUserName.Text);
           foreach (var attachment in Attactments)
       {
         m.Attachments.Add(new Attachment(attachment));
       }
         client.Send(m);
         m.To.Clear();
         m.Attachments.Clear();
         Success.Add(dr[0].ToString());
       }
         catch (SmtpException esException)
       {
         Errors.Add("Error sending to " + dr[0].ToString() + " " + esException.Message);
       }
         catch (Exception ex)
       {
         Errors.Add("Error sending to " + dr[0].ToString() + " " + ex.Message);

       }

我正在使用此工作代码的方法是循环遍历电子邮件地址和联系人姓名的数据表,因此只需将dr []。ToString()替换为您应该使用的值。