method for Sending email through Gmail SMTP server with C#

First you have to write the following code in web.config file:

  <add key="SmtpServer" value=""/>
  <add key="smtpserverport" value="587"/>
  <add key="FromId" value=""/>


The following Method will show an idea to send a mail through smpt server...

public void mailsend(string mailId, string subject, string body)
        string smtpServer = ConfigurationManager.AppSettings["SmtpServer"].ToString();
        int smtpserverport = Convert.ToInt32(ConfigurationManager.AppSettings["smtpserverport"]);

        MailMessage mailMsg = new MailMessage();
        mailMsg.From = new System.Net.Mail.MailAddress(ConfigurationManager.AppSettings["FromId"], "HIHL-1056", System.Text.Encoding.UTF8);
        mailMsg.Subject = subject;
        mailMsg.Body = body;
        mailMsg.BodyEncoding = System.Text.Encoding.UTF8;
        mailMsg.IsBodyHtml = true;
        mailMsg.Priority = System.Net.Mail.MailPriority.High;
        //The SMTP requires Authentication so the credentials has to be sent

        System.Net.NetworkCredential mailAuthentication = new System.Net.NetworkCredential("", "password");

        System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
        client.Port = smtpserverport;
        client.Host = smtpServer;
        client.EnableSsl = true;
        client.UseDefaultCredentials = false;
        client.Credentials = mailAuthentication;

        object userState = mailMsg;



1 comment: