0

I am sending emails using amazon java sdk. I have to send html template as mail. I have written a program for this and it is working fine. But now I am storing the whole html code in a single String. But whenever i need to edit the template, I have to edit the program (I mean the String variable). And also I have to take care the special characters like " \ ...etc in that html code. Please suggest me an elegant way to solve this issue.

3
  • do you mean you have the template hard coded in a java class ? or that you read a file and stiore the content of the file in a String ? i guess the first so just store the html as file and read it when you need it from that file Commented Dec 11, 2012 at 7:41
  • @Peter Yes. Noe I have hard coded it inside my java class. I know it is not a good way. Commented Dec 11, 2012 at 7:44
  • 1
    As Andrey Adamovich said, use template engine. I recommend Freemarker which is easy to use. Commented Dec 11, 2012 at 7:45

4 Answers 4

2

Use a template engine for that and store your template externally either in class path or on a file system. Here is a question that may help you selecting one: https://stackoverflow.com/questions/2381619/best-template-engine-in-java

Sign up to request clarification or add additional context in comments.

Comments

1

Use Apache Common Lang api's StringEscapeUtils#escapeHtml, It escapes the characters in a String using HTML entities and return a new escaped String, null if null string input.

For example:

"US" & "UK"

becomes:

"US" & "UK".

Comments

1

Check the Apache Velocity Project. You can create template for several things. From it's user-guide page

Velocity can be used to generate web pages, SQL, PostScript and other output from templates. It can be used either as a standalone utility for generating source code and reports, or as an integrated component of other systems.

You can use a VTL(Velocity Template Language) . A example from above link

<HTML>
<BODY>
Hello $customer.Name!
<table>
#foreach( $mud in $mudsOnSpecial )
   #if ( $customer.hasPurchased($mud) )
      <tr>
        <td>
          $flogger.getPromo( $mud )
        </td>
      </tr>
   #end
#end
</table>

Comments

0

Better and easiest way is reading the html file line by line using simple file reading operation and append this each line to a single String. And also I found this solution (also a better one, if you are ready to add one more library file to your project) from SO.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.