C# Send Email (with \r\n Line Breaks for Non-HTML or
for HTML

The .NET System.Message class allow for isHTMLBody to be true or false. Setting to true allows you to use HTML to make fields bolds, to use headers, to change colors, fonts, etc… But sometimes you prefer just a text email. In an HTML email, you cna use

 (break HTML) to create new lines.  In a non-HTML, you can use \r\n or System.EnvironmentNewLine, but only if you set a couple of other parameters (BodyEncoding , BodyTransferEncoding). 

C# Class Library

<pre>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Mail;

namespace Demo.Common.Helpers
{
    public class Mail
    {
        //send an email alert
        public static void sendEmail(string recipient, string subject, string message, bool isBodyHTML)
        {
            try
            {
                // Could make these two parms or config file parameters 
                string from = "noreply@YourDomain.com";  
                string host = "smtp.YourDomain.com";
                int smtpPort = 25;

                //append the System/Enviornment Name to the email subject
                //string systemEnvironmentName = Config.getConfigValue("systemName");
                //subject = subject.Trim() + " [" + systemEnvironmentName.Trim() + "]";

                MailMessage mail = new MailMessage();
                mail.IsBodyHtml = isBodyHTML;
                if (!isBodyHTML)
                {
                    // https://stackoverflow.com/questions/5020469/how-to-create-a-multi-line-body-in-c-sharp-system-net-mail-mailmessage
                    // next two lines to allow for \r\n new lines in text email 
                    mail.BodyEncoding = Encoding.UTF8;
                    mail.BodyTransferEncoding = System.Net.Mime.TransferEncoding.EightBit;
                }
                SmtpClient client = new SmtpClient();

                //set the email address from address
                MailAddress fromEmail = new MailAddress(from);
                mail.From = fromEmail;

                //split the recipient email address by ';' and add
                foreach (var address in recipient.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
                {
                    mail.To.Add(address);
                }

                client.Port = smtpPort;
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.UseDefaultCredentials = false;
                client.Host = host;
                mail.Subject = subject;
                mail.Body = message;

                client.Send(mail);
            }
            catch (SmtpException ex)
            {
                //LoggingToFiles.logHelperError("sendEmail", ex.Message);
                throw new Exception("SMTP.Exception in function sendEmail: " + ex.Message);
            }
            catch (Exception ex)
            {
                //LoggingToFiles.logHelperError("sendEmail", ex.Message);
                throw new Exception("Exception in function sendEmail: " + ex.Message);
            }
        }

    }

}
</pre>

Tester Program

<pre>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Demo.Common.ConsoleTests
{
    class TesterProgram
    {
        static void Main(string[] args)
        {

            // Demo non-HTML 
            Demo.Common.Helpers.Mail.sendEmail("youremail@abc.com", "Test line break", "Line1\r\nLine2\r\nLine3", false);

            // Demo HTML 
            Demo.Common.Helpers.Mail.sendEmail("youremail@abc.com", "Test line break", "<h4>Line1</h4><br />Line2<br />Line3", true);

            Console.WriteLine("\n\nPress enter to end:");
            Console.ReadLine();
        }
        
    }
}
</pre>

The trick for non-HTML was found here on StackOverflow

Uncategorized  

Leave a Reply