Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send an email to multiple recipients in Spring

Tags:

java

email

spring

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 work?

public void sendMail(String from, String[] to, String subject, String msg, List attachments) throws MessagingException {      // Creating message       sender.setHost("smtp.gmail.com");     MimeMessage mimeMsg = sender.createMimeMessage();     MimeMessageHelper helper = new MimeMessageHelper(mimeMsg, true);     Properties props = new Properties();     props.put("mail.smtp.starttls.enable", "true");     props.put("mail.smtp.auth", "true");     props.put("mail.smtp.port", "425");      Session session = Session.getDefaultInstance(props, null);      helper.setFrom(from);      helper.setTo(to);      helper.setSubject(subject);     helper.setText(msg + "<html><body><h1>hi welcome</h1><body></html", true);      Iterator it = attachments.iterator();      while (it.hasNext()) {         FileSystemResource file = new FileSystemResource(new File((String) it.next()));         helper.addAttachment(file.getFilename(), file);     }      // Sending message       sender.send(mimeMsg); } 
like image 327
Program-Me-Rev Avatar asked Nov 11 '14 14:11

Program-Me-Rev


People also ask

How do I send an email to multiple recipients in Java?

Sending Email to Multiple RecipientsFor adding Email in 'TO' field, you may use Message.RecipientType.To . Similarly for adding Email in 'CC' and 'BCC' fields, you will have to use Message.RecipientType.CC and Message. RecipientType. BCC.

How do I send to multiple email addresses in SMTP?

In short, to send to multiple recipients you should set the header to be a string of comma delimited email addresses. The sendmail() parameter to_addrs however should be a list of email addresses.


2 Answers

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("[email protected],[email protected]")) helper.setTo(new String[]{"[email protected]", "[email protected]"}); 

enter image description here

like image 138
Jens Avatar answered Sep 18 '22 20:09

Jens


The better approach is to create an array containing the address of multiple recipients.

    MimeMessageHelper helper = new MimeMessageHelper( message, true );     helper.setTo( String[] to ); 
like image 38
Surya Nair Avatar answered Sep 16 '22 20:09

Surya Nair