C# smtp 异常 发送邮件失败?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13506623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:47:49  来源:igfitidea点击:

smtp exception Failure sending mail?

c#asp.netsmtp

提问by vini

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("[email protected]");
    // Recipient e-mail address.
    Msg.To.Add("[email protected]");
    Msg.CC.Add("[email protected]");
    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);
}

Added this code in web.config

在 web.config 中添加了此代码

<appSettings>
    <add key="HostName"   value="The host name as given by my company" />
    <add key="PortNumber" value="25" />
</appSettings>

I keep getting an exception tried changing the port number as specified but no success

我不断收到异常尝试更改指定的端口号但没有成功

Exception Detail

异常详情

  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: 

采纳答案by Hiral

You need to give Username and password for smtp.

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

Use Below code :-

使用下面的代码:-

    MailSettings.SMTPServer = Convert.ToString(ConfigurationManager.AppSettings["HostName"]);
    MailMessage Msg = new MailMessage();
    // Sender e-mail address.
    Msg.From = new MailAddress("[email protected]");
    // Recipient e-mail address.
    Msg.To.Add("[email protected]");
    Msg.CC.Add("[email protected]");
    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);

回答by Ben

First, you don't need to manually read the values in your .config file. You can set the in the System.Net section and your SmtpClient object will read them automatically:

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

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

Then, from your code, you just write:

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

        SmtpClient smtp = new SmtpClient();
        MailMessage mailMessage = new MailMessage();
        mailMessage.To.Add(new MailAddress("[email protected]", "Recipient Display Name"));
        mailMessage.Subject = "Some Subject";
        mailMessage.Body = "One gorgeous body";
        smtp.Send(mailMessage);

Coming back to your error, it would appear you have some kind of a network problem.

回到你的错误,看起来你有某种网络问题。

回答by Anh Hoang

I suggest you the simplest way to send email on exception - using Elmah. Please follow this guide line for the solution: https://www.stormconsultancy.co.uk/blog/development/tools-plugins/setup-email-alerts-from-elmah-when-exceptions-are-raised/

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

回答by venkatesh

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);
           }

回答by the.net-learner

Another reason for this exception could be the anti virus installed on your system. This may be prohibiting the application to send mails. Just look out for a dialog box that is asking for permission to send mails through an application on your system.

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