Search code examples
c#asp.netskpsmtpmessage

Encode HTML in SMTP Message


I am new to trying the SMTPClient and would like to send a HTML formatted email to customers. The email message instead contains all the tags and not a formatted document. This is my code:

public void SendMailMessage(string FromAddress, string FromName, string ToName, string ToAddress, string Subject)
{
    MailAddress fromAdd = new MailAddress(FromAddress, FromName);
    MailAddress toAdd = new MailAddress(ToAddress);
    MailMessage msg = new MailMessage(fromAdd, toAdd);
    msg.IsBodyHtml = true;
    msg.BodyEncoding = System.Text.Encoding.UTF8;
    msg.Subject = Subject;
    string HtmlContent = "<div id='emailFormat' style='width: 100%; background-color: #efeac9;'>" +
                       "< div id = 'emailMsg' style = 'margin-left: auto; margin-right: auto; width: 600px; margin-top: 15px; font-family: Tahoma; font-size: .9em;' ><h2>Hello World</h2></div></div>");
    msg.Body = HtmlContent;
    SmtpClient client = new SmtpClient();
    client.Send(msg);
}

}

The email message looks like this:

Susan Farrar Today at 5:45 PM [email protected]

Message body

< div id = 'emailMsg' style = 'margin-left: auto; margin-right: auto; width: 600px; margin-top: 15px; font-family: Tahoma; font-size: .9em;' >

Hello World


Solution

  • The whitespace is causing the issue. You should change this:

    < div id = 'emailMsg' ...
    

    To this:

    <div id = 'emailMsg' ...