Send email in C#


Here are below the code the config to send a email through smtp server.

MailMessage msg = new MailMessage();
msg.From = new MailAddress("gmailAccount");//An gmail email address
msg.To.Add(_EmailTo);//_EmailTo is the reciever's email address
msg.Subject = txtSubject.Text;//the subject of my email
msg.Body = txtContent.Text;//the content of my email
msg.Priority = MailPriority.High;
//Attachment att = new Attachment("C:\test.txt");
//msg.Attachments.Add(att);
msg.SubjectEncoding = Encoding.UTF8;//support to send email with unicode character
msg.BodyEncoding = Encoding.UTF8;
msg.IsBodyHtml = true;//support email with html to format to display in the reciever's inbox

SmtpClient client = new SmtpClient();
client.Credentials = new NetworkCredential(_EmailFrom, _PasswordFrom);
client.Host = "smtp.gmail.com";
client.Port = 587; //this is have to be port 587
client.EnableSsl = true;
client.Send(msg);

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.