如何在春季向多个收件人发送电子邮件

2022-09-01 09:31:24

电子邮件仅发送到阵列中的最后一个电子邮件地址。我打算发送到添加到数组中的所有电子邮件地址。我怎样才能做到这一点?String[] to

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

答案 1

您可以选择使用以下 4 种方法。我提供了在这种情况下有用的两种方法的示例。我从下面的评论员那里整合了这一信息。

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

来自 Javadoc

enter image description here


答案 2

更好的方法是创建一个包含多个收件人地址的数组。

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

推荐