我有一个 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/