user2816714
user2816714

Reputation: 67

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

Upvotes: 0

Views: 2081

Answers (2)

Henrik Nielsen
Henrik Nielsen

Reputation: 410

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

< div id = 'emailMsg' ...

To this:

<div id = 'emailMsg' ...

Upvotes: 0

Xaver
Xaver

Reputation: 1041

The problem is that the content of string HtmlContent is not a well-formed HTML document. You are missing tags like <html>, <head>, <title>, <body>. Also, the additional space in < div is incorrect.

Upvotes: 1

Related Questions