Sending Automatic Email from Application to Users is a necessary task, in this post I want to show you how to send Email by using c#.
My Solution is Automatically Connect to a smtp mail server and use that to send email. To connect to a SMTP Server we need connection information from that server. In this post, I want to connect to gmail SMTP Server. below you see Gmail SMTP Server Connection Information :
- smtp Server : smtp.gmail.com
- smtp port : 587
now, I use my gmail Credential to send Email.
See Code below :
try
{
MailMessage message = new MailMessage();
SmtpClient smtp = new SmtpClient();
message.From = new MailAddress("codetipsacademy@gmail.com");
message.To.Add(new MailAddress("codetips@codetipsacademy.com"));
message.Subject = "Test Subject";
message.BodyEncoding = Encoding.UTF8; // Support UTF-8 Encoding
message.IsBodyHtml = true; // Message Body is Html
message.Body = "<b>Test Email</b><br /><p style='color:red;'>This is for Test</p>";
smtp.Port = 587; // Gmail SMTP SSL Support Port
smtp.Host = "smtp.gmail.com"; // Gmail SMTP Server
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("[Gmail Address]", "[Gmail Password]"); //Gmail Credential to Login
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(message);
Console.WriteLine("Success");
Console.ReadLine();
}
catch (Exception ex) {
Console.WriteLine("Error");
}
In code above fill [Gmail Address] with your Gmail Address and [Gmail Password] with your Gmail Password.

Due to the fact that Gmail block connection from apps by default. you should change this behaviour. So, in google account management setting, go to Security section, then, Allow “Less Secure App access”. see image below for help
