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

我有一个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();

当我在控制台上打印时,我从UI获取邮件ID,因为所有这三个都带有分离器recipientabc@gmail.com,efg@gmail.com,123@gmail.com,


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


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


ibeautiful
浏览 210回答 3
3回答

慕桂英4014372

这是一个字符串,由以下部分分隔的电子邮件ID组成:toAddress,if (toAddress!= null) {&nbsp; &nbsp; List<String> emails = new ArrayList<>();&nbsp; &nbsp; if (toAddress.contains(",")) {&nbsp; &nbsp; &nbsp; &nbsp; emails.addAll(Arrays.asList(toAddress.split(",")));&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; emails.add(toAddress);&nbsp; &nbsp; }&nbsp; &nbsp; Address[] to = new Address[emails.size()];&nbsp; &nbsp; int counter = 0;&nbsp; &nbsp; for(String email : emails) {&nbsp; &nbsp; &nbsp; &nbsp; to[counter] = new InternetAddress(email.trim());&nbsp; &nbsp; &nbsp; &nbsp; counter++;&nbsp; &nbsp; }&nbsp; &nbsp; message.setRecipients(Message.RecipientType.TO, to);}

宝慕林4294392

根据你的描述,我假设参数可以有多个值。因此是错误的。email-idsString recipient = request.getParameter("email-ids");我将引用ServletRequest.getParamter(String)上的Javadoc(由我强调):仅当确定参数只有一个值时,才应使用此方法。如果参数可能有多个值,请使用 。getParameterValues所以它应该是相反的。(您也可以尝试拆分代码中获得的单个字符串,但如果您已经获得了多个值,那么再次连接并拆分它们只会感觉错误且有风险。String[] recipients = request.getParameterValues("email-ids");有了这些单独的字符串,为已经在使用的数组创建多个元素应该没有问题。InternetAddress[] toAddresses

慕运维8079593

使用&nbsp;InternetAddress.parse&nbsp;方法。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java