Search code examples
javaspringemailsettext

Send values from List<> with setText() method in mail through spring


I have a List having values which I want to send through mail. But in mail I AM only getting the last value, rather then all values. Below is my code

private String sName[];
private String sID[];
 method abc()
{
  some code.....
 final int numberOfStudentsAdded = recentlyJoinedStudents.size();
 sName= new String[numberOfStudentsAdded];
 sID=new String[numberOfStudentsAdded]
for(int i=0;i<numberOfStudentsAdded;i++)
    {
        for(final Student s :recentlyJoinedStudents )
        {
            sName[i]=s.getName();
            sID[i]=s.getId();
        }
        message.setText(
                "<table><tr><td><h6>Student Name</h6></td><td><h6>Student ID</h6></td></tr><tr><td>"
                        + sName[i] + "</td><td>" + sID[i] + "</td><td></tr></table>", true);

    }}

Problem with above code is suppose I have 3 students in my list. But it gives record of last student. I want required output as

Student Name Student ID

abc 1

xyz 2

pqr 3

but I am getting output as

Student Name Student ID

pqr 3

How can I achieve that. What is wrong in my code.


Solution

  • You are overwritten all the time with the text message property with message.setText(""). And I do not understand the two loops. Try this piece of code instead :)

        String text = "<table><tr><td><h6>Student Name</h6></td><td><h6>Student ID</h6></td></tr>";
        for(int i=0;i<recentlyJoinedStudents.size();i++) {
            text += "<tr><td>" + recentlyJoinedStudents.get(i).getName() + "</td><td>" 
                    + recentlyJoinedStudents.get(i).getId() + "</td><td></tr>";
        }
        text += "</table>";
        System.out.print(text);