Search This Blog

Monday, September 26, 2011

How do I change the SMTP port number dynamically in asp.net

Use below method to set dynamic port while sending the email using SMTP

public static void SendMailwithDynamicPort(string strSmtpHost, int strPort, string strMessageBody, string strFrom, string strTo, string strSubject)
        {
            // Create and configure the smtp client
            SmtpClient smtpClient = new SmtpClient();
            if (strSmtpHost != null && strSmtpHost.Length > 0)
            {
                smtpClient.Host = strSmtpHost;
            }
            smtpClient.Port = strPort; // you can read from config
            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;

            MailMessage mailMessage = new MailMessage();
            mailMessage.Body = strMessageBody;
            mailMessage.From = new MailAddress(strFrom);
            mailMessage.To.Add(strTo);
            mailMessage.Subject = strSubject;
            mailMessage.Priority = MailPriority.Normal;//to set the email property

            smtpClient.Send(mailMessage);
        }

or through Web.Config also we can set port number

<configuration>
  <!-- Add the email settings to the <system.net> element -->
  <system.net>
    <mailSettings>
      <smtp>
        <network 
             host="relayServerHostname" 
             port="portNumber"
             userName="username"
             password="password" />
      </smtp>
    </mailSettings>
  </system.net>

  <system.web>
    ...
  </system.web>
</configuration>
Post a Comment

Popular Posts