The email gets sents only to the last email address in the String[] to
array. I\'m intending to send to all email addresses added to the array. How can I make that
It's working well with the SimpleMailMessage. like the answer of Siri
String[] to = {"user1@gmail.com", "user2@gmail.com"};
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setTo(to);
simpleMailMessage.setSubject("subject of mail");
simpleMailMessage.setText("content of mail");
try {
javaMailSender.send(simpleMailMessage);
} catch (MailSendException e) {
//...
}
The better approach is to create an array containing the address of multiple recipients.
MimeMessageHelper helper = new MimeMessageHelper( message, true );
helper.setTo( String[] to );
just try like this.
helper.setTo(InternetAddress.parse("email1@test.com,email2@test.com"))
I think better approach is to declare "to" attribute as array in spring.xml file , pass values and use method setTo(string[])
as suggested by Deinum in comment. Process is define 'to' in xml file as
<property name="to">
<array>
<value>abc@gmail.com</value>
<value>xyz@gmail.com</value>
</array>
</property>
Now generate getter setter method for this array containing address of multiple recipient and pass it to setTo(String[])
method as :-
helper.setTo(to);
Add all email ids in a String[] array
public String[] sendEmailIds() {
String[] emailIds = new String[4];
emailIds[0] = "abc@mail.com";
emailIds[1] = "deg@mail.com";
emailIds[2] = "sgh@mail.com";
emailIds[3] = "hht@mail.com";
return emailIds;
}
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setTo(sendEmailIds());
mailMessage.setSubject(subject);
mailMessage.setText(message);
mailMessage.setFrom(fromEmailAddress);
javaMailSender.send(mailMessage);
You have the choice to use the following 4 methods. I have provided examples of the two methods useful in this case. I have consolidated this information from the commentators below.
helper.setTo(InternetAddress.parse("email1@test.com,email2@test.com"))
helper.setTo(new String[]{"email1@test.com", "email2@test.com"});