ComponentPro UltimateMail

      Handling exceptions

      Language Filter: AllSend comments on this topic to ComponentPro

      Handling Exceptions

      Exceptions thrown by Mail component can be easily caught by using try catch block. The table below lists all exceptions relating to the Mail component: 

      Exception Description
      SmtpException The exception that is thrown when an error occurs while using Smtp classes.
      MailException The exception that is thrown when an e-mail related error occurs.
      ProxySocketException The exception that is thrown when a proxy error or socket error occurs.

      The example below shows how to handle exceptions:

      using System;
      using ComponentPro.Net;
      using ComponentPro.Net.Mail;
      
      ...
      
      // SMTP server information. 
      const string serverName = "myserver";
      const string user = "name@domain.com";
      const string password = "mytestpassword";
      const int port = 465;
      const SslSecurityMode securityMode = SslSecurityMode.Implicit;
      
      // Create a new instance of the Smtp class.
      Smtp client = new Smtp();
      
      try
      {
          // Connect to the server. 
          client.Connect(serverName, port, securityMode);
      
          // Login to the server. 
          client.Authenticate(user, password);
      
          // Create a new mail message. 
          MailMessage msg = new MailMessage();
          msg.Subject = "Test Subject";
          msg.BodyText = "Content";
          msg.From = "from@mydomain.com";
          msg.To = "to@somedomain.com";
      
          // And send it. 
          client.Send(msg);
      
          // Close the connection. 
          client.Disconnect();
      }
      catch (Exception exc)
      {
          // Show error. 
          Console.WriteLine("Error: " + exc.Message);
      
          // Safely disconnect. 
          if (client.IsConnected)
              client.Disconnect();
      }