How to send an email to multiple recipients in Spring

Email is sent only to the last email address in the String[] to array. I am going to send all email addresses added to the array. How can I do this job?

 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); } 
+11
source share
6 answers

You have the choice to use the following 4 methods. I gave examples of two methods useful in this case. I have gathered this information from commentators below.

 helper.setTo(InternetAddress.parse(" email1@test.com , email2@test.com ")) helper.setTo(new String[]{" email1@test.com ", " email2@test.com "}); 

enter image description here

+16
source

The best approach is to create an array containing the address of several recipients.

  MimeMessageHelper helper = new MimeMessageHelper( message, true ); helper.setTo( String[] to ); 
+6
source

just try it like this.

 helper.setTo(InternetAddress.parse(" email1@test.com , email2@test.com ")) 
+2
source

You can try this, not

 helper.setTo(to); String multipleEmailIds = " abc@abc.com , abc@abc.com " mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(multipleEmailIds )); 
+1
source

I think the best approach is to declare the "to" attribute as an array in the spring.xml file, pass in the values, and use the setTo(string[]) method, as suggested by Deinum in the comment. The process defines 'to' in the xml file as

 <property name="to"> <array> <value> abc@gmail.com </value> <value> xyz@gmail.com </value> </array> </property> 

Now create a set getter method for this array containing the address of several recipients, and pass it to the setTo(string[]) method as: -

 helper.setTo(to); 
0
source
 <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="smtp.ccc.corp"/> <property name="port" value="25"/> <property name="javaMailProperties"><props> <prop key="mail.smtp.sendpartial">true</prop> </props></property> </bean> 

set mail.smtp.sendpartial true. I'm sure his work is for you

-3
source

Source: https://habr.com/ru/post/978031/


All Articles