How To Send An Email in Asp.Net Using Gmail

If your application doing more than displaying “Hello World” then we should need to configure the Email Services in your application. In this post I am going to create a static class so we can call this without creating a object of this class Static Class and Method

public static class EmailServices
{
public static void SendMail(string htmlBody)
{
var message = new MailMessage { From = new MailAddress("your@domainname.com") };
message.To.Add("Hello@bro.com");// Add receiptants
message.CC.Add("cc@email.com");
message.Subject = "Send Email using Gmail"; //Add Subject
message.IsBodyHtml = true;
message.Body = htmlBody;//Text Box for body
message.Priority = MailPriority.High;

var client = new SmtpClient("smtp.gmail.com", 587)
{
UseDefaultCredentials = false,
Credentials = new System.Net.NetworkCredential("Google's username", " password"), // replace with your correct Gmail's username and password
Port = 587,
Host = "smtp.gmail.com",
EnableSsl = true
};

client.Send(message);
}

}

  If you want to send more email at a time then you simply need to create a list of string then pass to the Add cc or To methods example are as follows: var emails = new List<string> {“First@email.com”, “Second@email.com”, “Third@email.com”}; message.To.Add(emails); message.CC.Add(emails); Note: Don’t changeĀ  HostName and PortNumber otherwise this will not work as expected. Enjoy

Leave a Reply