smtp exception Failure sending mail?

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("<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2353525163444e424a4f0d404c4e">[email protected]</a>");
    // Recipient e-mail address.
    Msg.To.Add("<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2f4e4d4c6f48424e4643014c4042">[email protected]</a>");
    Msg.CC.Add("<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fb81989fbb9c969a9297d5989496">[email protected]</a>");
    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

<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-TFSAFSSCodeERPNETPAYMENTDTALinesfollowup.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:

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You need to give Username and password for smtp.

Use Below code :-

    MailSettings.SMTPServer = Convert.ToString(ConfigurationManager.AppSettings["HostName"]);
    MailMessage Msg = new MailMessage();
    // Sender e-mail address.
    Msg.From = new MailAddress("<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6010111220070d01090c4e030f0d">[email protected]</a>");
    // Recipient e-mail address.
    Msg.To.Add("<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a5c4c7c6e5c2c8c4ccc98bc6cac8">[email protected]</a>");
    Msg.CC.Add("<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d5afb6b195b2b8b4bcb9fbb6bab8">[email protected]</a>");
    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);

Method 2

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:

<system.net>
    <mailSettings>
      <smtp from="Sender's display name &lt;<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="becddbd0dadbcce1dbd3dfd7d2fedad1d3dfd7d090ddd1d3">[email protected]</a>&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("<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b9cbdcdad0c9d0dcd7cdf9cad6d4dcddd6d4d8d0d797dad6d4">[email protected]</a>", "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.

Method 3

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/

Method 4

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

Method 5

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x