How to send an email to multiple recipients in Spring

前端 未结 8 2219
花落未央
花落未央 2021-02-12 10:48

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

相关标签:
8条回答
  • 2021-02-12 11:14

    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) {
         //...
    }   
    
    0 讨论(0)
  • 2021-02-12 11:15

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

        MimeMessageHelper helper = new MimeMessageHelper( message, true );
        helper.setTo( String[] to );
    
    0 讨论(0)
  • 2021-02-12 11:16

    just try like this.

    helper.setTo(InternetAddress.parse("email1@test.com,email2@test.com")) 
    
    0 讨论(0)
  • 2021-02-12 11:26

    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);
    
    0 讨论(0)
  • 2021-02-12 11:28

    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);
    
    0 讨论(0)
  • 2021-02-12 11:31

    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"});
    

    0 讨论(0)
提交回复
热议问题