Home > Back-end >  HTML template is displayed in email body
HTML template is displayed in email body

Time:12-26

We have an HTML file saved as string in DB. This html has a template tag "OrderProductsDetails" inside, and we have special method to replace each placeholder, {{var}} or {{%var}}, with its corresponding value.

<!DOCTYPE html>
<html> 
    <body>
        <template id="OrderProductsDetails">
            Product: {{%Name}} <br/>
            Quantity: {{%Quantity}} <br/>
            Amount: {{%TotalCost}}<br/>
        </template>
              
        <b> Order details: </b> <br/>
        Order Id: {{OrderId}} <br/>
        Order time: {{OrderCreatedAt}} <br/>
        Order type: {{OrderSide}} <br/>
        <b>Products details:</b>  <br/> 
        {{OrderProductsDetails}} <br/>
    </body>
</html>

This html file is displayed normally in browser. i.e. the template tag is not shown.

But the problem happens when try to send this file as email body, using System.Net.Mail.MailMessage:

MailMessage message = new MailMessage(from, to)
{
    Body = MyHtmlFileFromDB,
    IsBodyHtml = true,
    BodyEncoding = System.Text.Encoding.UTF8,
    Subject = "Temp email",
    SubjectEncoding = System.Text.Encoding.UTF8
};

The email body shows the template content on top of the email like this:

Product: {{%Name}}
Quantity: {{%Quantity}}
Amount: {{%TotalCost}}

Order details:
Order Id: 2850
Order time: 12/25/2022 11:46:15 AM
Order type: Buy
Products details:
Product: prodddd
Quantity: 1
Amount: 40,679.050

How can I make this template tag invisible in the email body?

CodePudding user response:

The email client will just see the entire HTML, unlike browser it will not hide the <template> tag. So, you need to write code that removes this 'template' element before setting the Message object's Body property.

  • Related