Вопрос

I will collect all the data from the database and put them inside a collection. I want to put all the data in that collection into my javamail body in the properly aligned format illustrated below. How should I put the list data inside the body content:

  EmployeeName:Ranjeeth.
  Login Time:09:30.
  Logout Time:18:30.

by using escape chars how to write in string?

Это было полезно?

Решение

One of the most common way to do this, is to create an email template with data placeholder. At runtime fill the data in the template and then use the complete text in the java mail body.

Step wise:

  1. Create a template file say mailBody.txt in the project. The content could be like this:

    EmployeeName: ##EMP_NAME##.

    Login Time:##LOGIN_TIME##.

    Logout Time:##LOGOUT_TIME##.

  2. Read this file content in a string at runtime, so that :

    See this How to really read text file from classpath in Java

Read content from inpitstream

    InputStream is = new FileInputStream("test");  // or your input stream
    byte[] b = new byte[is.available()];
    is.read(b);
    String text = new String(b);
    //System.out.println(text);

`String s = <content of the file>`

3. Prepare the data from database and then replace the String content placeholders like:

s = s.replace("##EMP_NAME##", <emp name value from database>)

s = s.replace("##LOGIN_TIME##", <login time value from database>)

s = s.replace("##LOGOUT_TIME##", <logout value from database>)

  1. use the String s for the email body content.

You can add any kind of formatting, tabs, spaces etc in the template and your program would change the email text seamlessly.


Edit: To Repeat a certain part again and again: If you have simple data to repeat, just think about creating it inline like:

StringBuilder temp=new StringBuilder("");
for(loop to repeat the content){
temp.append(<Emp Name value from database>).append("\n\t\t")
.append(<login time value from database>).append("\n\t\t")
.append(<logout time value from database>).append("\n\t\t");
}

make template like:

Hi,

Below is the details of users:

$#EMP_DETAILS#$

Thanks, Your Name

Read the template into string variable

String s = <content of the file>;

then

s.replace("$#EMP_DETAILS#$", temp.toString());

You should be all set.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top