Monday, 17 October 2016

Sending Email via SMTP client


Simple Mail Transfer Protocol commonly known as SMTP is the protocol for sending and receiving email. .NET allows to use this SMTP service via its SMTP client.

Consider the below code:

System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587);
                            smtpClient.UseDefaultCredentials = false;
                            smtpClient.Credentials = new System.Net.NetworkCredential("abc@live.com", "hr1?");
                            smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                            smtpClient.EnableSsl = true;
                            smtpClient.Timeout = 20000;
                            System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
                            
//Setting From , To and CC
                            mail.From = new System.Net.Mail.MailAddress("abc@live.com", "Game");
                            mail.To.Add(new System.Net.Mail.MailAddress("efg@live.com"));
                            smtpClient.Send(mail);


  • In the above code first an object of smptClient is created. 
  • Host server name (here smtp.gmail.com) and port number (here 587)  is provided as parameter.
  • We do not want to use default credentials here so just set the respective attribute of smtpClient to false.
  • Here we use the email "abc@live.com" with password "hr1?" as the sender credentials.
  • Delivery method of SMTP is set to Network so that mail is send via network.
  • EnableSsl is set true to make the transmission secure by SSL (secure socket layer)
  • Setting timeout of mail process to 20000 milliseconds (20 seconds)
  • Mail message object "mail" is instantiated.
  • Mail from (here abc@live.com with name "Game") and mail to (here efg@live.com) is set
  • smtpClient sends the provided mail with Send() function


No comments:

Post a Comment