Send HTML Email Using C#

Sending emails using code can be trivial but fear not, I’m going to show you how I accomplish it today in style by sending HTML emails using C#. Email clients are unpredictable. Even today many clients strip styles that are not inlined, so it is important to inline your CSS before sending. We will utilize inline CSS to keep things looking structured and great. You can find some great inline CSS HTML email templates online in all different styles that you can modify for your specific use case.
I’ve included the entire script below but before you copy and paste into your project I think it’s worthwhile to take a look and understand how this all works beforehand. Initially, you will notice the addition of a few using statements that will let us send emails and one to handle reading the HTML file. Then we go ahead and declare a new SmtpClient called “smpt”. In our start function, we will set up the Smtp Client. I will be using a Gmail account but if you are going to be using a different email client you’re going to need to find the host and port information from the client you’re using.
The next function we are going to have is the sendEmail function. This is where we will put the logic to create and send our email. First of we are going to use a StreamReader to read all the text from our HTML file and assign it to a string which we’ve named “emailBody”. Then we’ll create a new MailMessage variable named “mail”. Then we will set the properties of “mail”. There is a property called isBodyHtml which we’ll set to true. Then we can set the From, To, Subject, and Body properties. Our Body property will be equal to our emailBody string which contains all of our text from your HTML file. Lastly, we will use a try-catch statement and call smtp.Send(mail) to use our SmtpClient to send our MailMessage mail.

using System.Net;
using System.Net.Mail;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.IO;
public class Email {
    string emailBody;
    SmtpClient smtp = new SmtpClient();
    void Start () {
          smtp.Host = "";
          smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
          smtp.Credentials = newSystem.Net.NetworkCredential("", "password") as ICredentialsByHost;
          smtp.EnableSsl = true;
          delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
          { return true; };
     void sendEmail(string email){
          using (StreamReader reader = newStreamReader("C:/template.html"))
          emailBody = reader.ReadToEnd();
          MailMessage mail = newMailMessage();
          mail.IsBodyHtml = true;
          mail.From = newMailAddress("", "Sender Name");
          mail.Subject = "Your subject line!";
          mail.Body = emailBody;
            //Email sent
            //Email Not Sent