Search code examples
javaspecial-charactershtml-emailsymbols

How to display symbols in email body using java


I want to display special character or symbols in email body of a HTML email sent using Java. Below are the details of the problem.
I have created the extension which gets all the text entered in Text Box of form in webpage, I am storing this text in String variable and passing this variable as parameter to method responsible for sending email. If user puts special characters or symbols like "←" in Text Box it is displayed as "â†" in email body, how can I handle these special characters or symbols using java so that they will be displayed as it is in the email body

Here is what my code looks like

String description = "Here I am getting all text from Text box in webpage, it can also  
contain special character as explained above";
String emailSubject = "test HTML email";
String emailBody =  "<!DOCTYPE html>" + "<html>" + "<body>" +
"<p>Please review this work item and assign it to the appropriate owner.</p>" + description+
            "</body>" + "</html>";  
//below is the method responsible for sending email to which I pass string parameters emailSubject   
//and emailBody  

Solution

  • You can represent special symbols with HTML entities. You basically need to map symbols to HTML entities and replace them in string. For example arrow symbol that user inputs can be replaced in HTML with &larr; and will be displayed in HTML as ←.

    You can use this class to do this for you: https://commons.apache.org/proper/commons-text/apidocs/org/apache/commons/text/StringEscapeUtils.html