method for Sending email through Gmail SMTP server with C#

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

  <add key="SmtpServer" value="smtp.gmail.com"/>
  <add key="smtpserverport" value="587"/>
  <add key="FromId" value="xyz@gmail.com"/>

</appSettings>


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.To.Add(mailId);
        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("xyz@gmail.com", "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;

        client.Send(mailMsg);

    }

1 comment: