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

时间:2019-03-27 09:46:07

标签: java servlets javamail

我有一个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时,我从用户界面获得的邮件ID为abc@gmail.com,efg@gmail.com,123@gmail.com,所有三个都使用,分隔符

只有一个收件人时,这个人就可以正常工作,但是如果有一个以上的收件人,我不知道该怎么做

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

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

根据您的描述,我假设参数email-ids可以具有多个值。因此String recipient = request.getParameter("email-ids");是错误的。

我会引用Javadoc on ServletRequest.getParamter(String)(我强调):

  

仅在确定参数只有一个值时,才应使用此方法。如果参数可能有多个值,请使用getParameterValues

因此应改为String[] recipients = request.getParameterValues("email-ids");。 (您也可以尝试拆分代码中得到的单个字符串,但是如果您已经获得了多个值,那么再级联并拆分它们只会感到错误和冒险。)

使用这些单独的字符串,为已经使用的数组InternetAddress[] toAddresses创建多个元素应该没问题。

答案 2 :(得分:0)

使用InternetAddress.parse方法。