Not logged in - Login
< back

Sending mail via SMTP

This is an example of how to send an email via SMTP and optionally log into the inbox before connecting to the SMTP server.

public static void SendMail(System.Net.Mail.MailMessage msg)
{
    // do the contract validation here.
    System.Diagnostics.Contracts.Contract.Requires(msg != null, "Parameter 'msg' cannot be null.");
    
   using (System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient())
   {
      // get the mail configuration settings.
      string host = "mail.myserver.com";
      string pop3host = "mail.myserver.com";
      int port = 25;
      string userName = "john@myserver.com";
      string password = "pass@word1";
      bool isSecure = true;
      bool loginToInbox = true;

      // Create an instance of the SMTP object.
      using (System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient())
      {   
         // Set the host and port for the SMTP client
         smtp.Host = host;
         smtp.Port = csWeb.Classes.WebUtility.GetConfigSettingInt("SmtpPort"); //1025;

         // Create an instance of the Network Credentials object.
         System.Net.NetworkCredential cred = new System.Net.NetworkCredential();

         // Set the Username & Password
         cred.UserName = userName;
         cred.Password = password;

         // This value needs to be set to false BEFORE setting the credentials.
         smtp.UseDefaultCredentials = false;
         // Set the credentials for the SMTP object.
         smtp.Credentials = cred;

         // if we are to user a secure connection, set it here
         if (bSecure) smtp.EnableSsl = true;

         // 
         if (bLoginToInbox)
         {
            // get a socket, use our helper class to do most of the work.
            using (Pop3Client pop3 = new Pop3Client(cred.UserName, cred.Password, pop3host))
            {
               // open the inbox.
               pop3.OpenInbox();
               // close the connection
               pop3.CloseConnection();
            }
         }   
         
         // Send the email
         smtp.Send(msg);
      }   
   }
}