[SalesForce] Get Email Body with HTML Tags

I want to send an email in my logic. I have created an Email Template.

Here is what I want to achieve:

Email Template:

<html width="600px">
<style>body{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;color: #31343c;font-size:14px;line-height:21px;}a{text-decoration:none;color:#03a2d6;}</style>
<body>
    <center>
        <div style="width:600px">
            <div style="height:80px;background-color:#17191d;text-align:left;"><img src="TEST" style="margin-top:15px !important;" /></div>
            <div style="padding-top:15px"></div>
            <font style="color:#ffffff; ">
            <b>Product: </b>
            PRODUCT_ID
            <br />
            <font style="color:#ffffff; "><b>Size: </b>
            CONDITIONAL_TEXT_1
            <br />
            <font style="color:#ffffff; "><b>Expiration Date: </b>
            DATE
            <font style="color:#989b9f ;font-size:11px;line-height: 16px;">
            EMAIL_FOOTER
            <br />
        </div>
    </center>
</body>
</html>

Now, I am querying the Email Template Body in my Code, and replacing the necessary labels with the values that I want to put.

The method being used is:

public static String createEmailBody(List<Object__c> Object){
    EmailTemplate tempID = [SELECT Id,Name,Body FROM EmailTemplate WHERE Id =: System.Label.TEMPLATEID];

    String emailBody = tempID.Body;
    String ObjectId= String.valueOf(Object[0].Product_Id__c);
    Integer ObjectSize= Integer.valueOf(Object[0].Size_GB__c);
    String expD = EC_Constants.BLANK;

    emailBody = emailBody.replace('PRODUCT_ID',ObjectId);

    if(Object[0].Size_GB__c != null) {
        emailBody = emailBody.replace('CONDITIONAL_TEXT_1',String.valueOf(ObjectSize));
    }

    if(Object[0].Time_Expires__c != null) {
        expD = (Object[0].Time_Expires__c.year() == 2038)?EC_Constants.PERP:Object[0].Time_Expires__c.Date().format();
    }

    emailBody = emailBody.replace('expD',expD);
    emailBody = emailBody.replace('EMAIL_FOOTER',System.Label.EMAIL_FOOTER);

    return emailBody;
}

This method sets the body of the email. I am sending the mail in another method, where I call the above method and get the body.

I am using Messaging.SendEmail method.
When I set the body of the mail, I am using:

mail.setHTMLBody(emailBody);

However, when I send the mail, all the HTML Tags are getting stripped, and the Plain Text version is being displayed. I can see no formatting.

WHere am I going wrong? Please help.

Best Answer

Sorry for the late response but I have finally got the answer for this. I was fetching ONLY THE BODY from the template, and not the HTML Body.

The appropriate query should have been this:

EmailTemplate tempID = [SELECT Id,HTMLValue,Name FROM EmailTemplate WHERE Id =: System.Label.TEMPLATEID];
String emailBody = tempID.HTMLValue;

This worked wonders.

Thanks a lot ! :)

Related Topic