smtp异常发送邮件失败?

时间:2012-11-22 05:54:26

标签: c# asp.net smtp

StringBuilder emailMessage = new StringBuilder();
emailMessage.Append("Dear Payment Team ,");
emailMessage.Append("<br><br>Please find the Payment instruction");    

try
{
    MailMessage Msg = new MailMessage();
    // Sender e-mail address.
    Msg.From = new MailAddress("pqr@gmail.com");
    // Recipient e-mail address.
    Msg.To.Add("abc@gmail.com");
    Msg.CC.Add("zcd@gmail.com");
    Msg.Subject = "Timesheet Payment Instruction updated";
    Msg.IsBodyHtml = true;
    Msg.Body = emailMessage.ToString();
    SmtpClient smtp = new SmtpClient();
    //smtp.EnableSsl = true;

    smtp.Host = ConfigurationManager.AppSettings["HostName"];
    smtp.Port = int.Parse(ConfigurationManager.AppSettings["PortNumber"]);
    smtp.Send(Msg);
    Msg = null;
    Page.RegisterStartupScript("UserMsg", "<script>alert('Mail has been sent successfully.')</script>");
}
catch (Exception ex)
{
    Console.WriteLine("{0} Exception caught.", ex);
}

在web.config

中添加了此代码
<appSettings>
    <add key="HostName"   value="The host name as given by my company" />
    <add key="PortNumber" value="25" />
</appSettings>

我一直在尝试更改指定的端口号,但没有成功

例外明细

  System.Net.Mail.SmtpException was caught
  Message=Failure sending mail.
  Source=System
  StackTrace:
       at System.Net.Mail.SmtpClient.Send(MailMessage message)
       at PAYMENT_DTALinesfollowup.Sendbtn_Click(Object sender, EventArgs e) in d:\AFSS-TFS\AFSS\Code\ERPNET\PAYMENT\DTALinesfollowup.aspx.cs:line 488
  InnerException: System.Net.WebException
       Message=Unable to connect to the remote server
       Source=System
       StackTrace:
            at System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6, Int32 timeout)
            at System.Net.PooledStream.Activate(Object owningObject, Boolean async, Int32 timeout, GeneralAsyncDelegate asyncCallback)
            at System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback)
            at System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout)
            at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)
            at System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint)
            at System.Net.Mail.SmtpClient.GetConnection()
            at System.Net.Mail.SmtpClient.Send(MailMessage message)
       InnerException: System.Net.Sockets.SocketException
            Message=A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 125.63.68.148:25
            Source=System
            ErrorCode=10060
            NativeErrorCode=10060
            StackTrace:
                 at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
                 at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
            InnerException: 

5 个答案:

答案 0 :(得分:5)

您需要为smtp提供用户名和密码。

使用以下代码: -

    MailSettings.SMTPServer = Convert.ToString(ConfigurationManager.AppSettings["HostName"]);
    MailMessage Msg = new MailMessage();
    // Sender e-mail address.
    Msg.From = new MailAddress("pqr@gmail.com");
    // Recipient e-mail address.
    Msg.To.Add("abc@gmail.com");
    Msg.CC.Add("zcd@gmail.com");
    Msg.Subject = "Timesheet Payment Instruction updated";
    Msg.IsBodyHtml = true;
    Msg.Body = emailMessage.ToString();
    NetworkCredential loginInfo = new NetworkCredential(Convert.ToString(ConfigurationManager.AppSettings["UserName"]), Convert.ToString(ConfigurationManager.AppSettings["Password"])); // password for connection smtp if u dont have have then pass blank

    SmtpClient smtp = new SmtpClient();
    smtp.UseDefaultCredentials = true;
    smtp.Credentials = loginInfo;
    //smtp.EnableSsl = true;
    //No need for port
    //smtp.Host = ConfigurationManager.AppSettings["HostName"];
    //smtp.Port = int.Parse(ConfigurationManager.AppSettings["PortNumber"]);
     smtp.Send(Msg);

答案 1 :(得分:2)

首先,您无需手动读取.config文件中的值。您可以在System.Net部分中进行设置,您的SmtpClient对象将自动读取它们:

<system.net>
    <mailSettings>
      <smtp from="Sender's display name &lt;sender_email@domain.com&gt;">
        <network host="mailserver.yourdomain.com" port="25" userName="smtp_server_username" password="secret" defaultCredentials="false" />
      </smtp>
    </mailSettings>
  </system.net>

然后,从您的代码中,您只需写下:

        SmtpClient smtp = new SmtpClient();
        MailMessage mailMessage = new MailMessage();
        mailMessage.To.Add(new MailAddress("recipient@somedomain.com", "Recipient Display Name"));
        mailMessage.Subject = "Some Subject";
        mailMessage.Body = "One gorgeous body";
        smtp.Send(mailMessage);

回到你的错误,你可能会遇到某种网络问题。

答案 2 :(得分:0)

我建议您使用Elmah在异常时发送电子邮件的最简单方法。请按照此指南获取解决方案: https://www.stormconsultancy.co.uk/blog/development/tools-plugins/setup-email-alerts-from-elmah-when-exceptions-are-raised/

答案 3 :(得分:0)

try
           {
               MailMessage mail = new MailMessage();
               //SmtpClient SmtpServer = new SmtpClient("smtp.google.com");
              SmtpClient SmtpServer = new SmtpClient(sServer);

              // SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com", 587);
               mail.From = new MailAddress(sFromEmailId);
               mail.To.Add(sToEmailId);
               mail.Subject = sSubject;
               mail.Body = sMessage;
               mail.IsBodyHtml = true;             
               HttpFileCollection hfc = Request.Files;
               for (int i = 0; i < hfc.Count; i++)
               {
                   HttpPostedFile hpf = hfc[i];
                   if (hpf.ContentLength > 0)
                   {
                       mail.Attachments.Add(new Attachment(fupload.PostedFile.InputStream, hpf.FileName));

                   }
               }
               SmtpServer.Port = 587;
               //SmtpServer.Host = "smtp.gmail.com";
               SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
               SmtpServer.UseDefaultCredentials = false;
               SmtpServer.Credentials = new System.Net.NetworkCredential(sFromEmailId, sPassword);
               SmtpServer.EnableSsl = true;
               SmtpServer.Send(mail);                
               ClientScript.RegisterStartupScript(this.GetType(), "Alert", "dim('Mail Sent Successfully..!');", true);
               mail.Dispose();
           }
           catch (Exception ex)
           {                
               ClientScript.RegisterStartupScript(this.GetType(), "Alert", "dim('Error in Sending Mail..!');", true);
           }

答案 4 :(得分:0)

此异常的另一个原因可能是系统上安装了反病毒。这可能会禁止应用程序发送邮件。只需注意一个对话框,要求允许通过系统上的应用程序发送邮件。