Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send HTML email via C# with SmtpClient

People also ask

How do I send an HTML formatted email?

On the Tools menu, click Options, and then click the Mail Format tab. Under Message Format, in the Compose in this message format list, click HTML or Plain Text, and then click OK.

Can you send HTML files via email?

The most important thing to know about HTML email is that you can't just attach an HTML file and a bunch of images to a message, then click send. Most of the time, your recipient's email application will break all the paths to your image files by moving your images into temporary folders on the recipient's hard drive.


This is what I do:

MailMessage mail = new MailMessage(from, to, subject, message);
mail.IsBodyHtml = true;
SmtpClient client = new SmtpClient("localhost");
client.Send(mail);

Note that I set the mail message html to true: mail.IsBodyHtml = true;


I believe it was something like:

mailObject.IsBodyHtml = true;

IsBodyHtml = true is undoubtedly the most important part.

But if you want to provide an email with both a text/plain part and a text/html part composed as alternates, it is also possible using the AlternateView class:

MailMessage msg = new MailMessage();
AlternateView plainView = AlternateView
     .CreateAlternateViewFromString("Some plaintext", Encoding.UTF8, "text/plain");
// We have something to show in real old mail clients.
msg.AlternateViews.Add(plainView); 
string htmlText = "The <b>fancy</b> part.";
AlternateView htmlView = 
     AlternateView.CreateAlternateViewFromString(htmlText, Encoding.UTF8, "text/html");
msg.AlternateViews.Add(htmlView); // And a html attachment to make sure.
msg.Body = htmlText;  // But the basis is the html body
msg.IsBodyHtml = true; // But the basis is the html body

Apply the correct encoding of the Mailbody.

mail.IsBodyHtml = true;

i have an idea , you can add a check box to your project for sending email as html as an option for user , and add this code to enable it :

         MailMessage mail = new MailMessage(from, to, subject, message);

         if(checkBox1.CheckState == CheckState.Checked )
           {
               mail.IsBodyHtml = true;
           }

         SmtpClient client = new SmtpClient("localhost");

         client.Send(mail);