java - 如何将邮件发送给多个收件人

标签 java servlets jakarta-mail

我有一个 HTML 表单,用户可以在其中输入多个邮件 ID,但我不知道如何向多个人发送邮件

我已成功向一位用户发送邮件,但在这里我陷入了发送多封电子邮件的困境。

我做了什么:

这是我的 EmailUntility 类:

public class EmailUtility {
public static void sendEmail(String host, String port, final String userName, final String password,
        String toAddress, String subject, String message) throws AddressException, MessagingException {


    Properties properties = new Properties();
    properties.put("mail.smtp.host", host);
    properties.put("mail.smtp.port", port);
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.starttls.enable", "true");
    Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, password);
        }
    });
    session.setDebug(false);
    Message msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress(userName));
    InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
    msg.setRecipients(Message.RecipientType.TO, toAddresses);
    msg.setSubject(subject);
    msg.setSentDate(new Date());
    msg.setText(message);

    Transport.send(msg);

}

}

这是我的 Servlet doPost

        String recipient = request.getParameter("email-ids");
    String subject = request.getParameter("subject");
    String content = request.getParameter("content");
    System.out.println(recipient);

    try {
        EmailUtility.sendEmail(host, port, user, pass, recipient, subject,
                content);

    } catch (Exception ex) {
        ex.printStackTrace();

当我在控制台上打印recipient时,我从UI获取邮件ID为abc@gmail.com,efg@gmail.com,123@gmail.com all三者以 , 分隔符

当只有一个收件人时,这个工作正常,但当有多个收件人时,我不知道该怎么做

我正在使用 java.mail api 发送邮件。

最佳答案

此处 toAddress 是由 , 分隔的电子邮件 ID 组成的字符串

if (toAddress!= null) {
    List<String> emails = new ArrayList<>();
    if (toAddress.contains(",")) {
        emails.addAll(Arrays.asList(toAddress.split(",")));
    } else {
        emails.add(toAddress);
    }
    Address[] to = new Address[emails.size()];
    int counter = 0;
    for(String email : emails) {
        to[counter] = new InternetAddress(email.trim());
        counter++;
    }
    message.setRecipients(Message.RecipientType.TO, to);
}

关于java - 如何将邮件发送给多个收件人,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55374113/

相关文章:

java - Intellij idea中无法按 "run"

java - servlet不加载jsp

android - 如何让 App Engine Servlet 监听 Firebase

java - tomcat web应用程序的并行编程

java - 如何创建带有变音符号和 unterscore 的邮件附件文件名?

java - 从 IMAP 读取电子邮件 - 处理时如何将其标记为“已读”?

java - 无法初始化类 org.springframework.osgi.service.importer.support.OsgiServiceProxyFactoryBean

java - 黑莓 java ListField

java - 从命令行更改 Ants 任务类路径

java : execute a method over a maximum period of time