在 Java 中向多个收件人发送邮件

2022-08-31 11:01:00

我想使用以下方法向多个收件人发送邮件:

message.addRecipient(Message.RecipientType.TO, String arg1);

message.setRecipients(Message.RecipientType.TO,String arg1);

但一个困惑是,在第二个参数中,如何传递多个地址,例如:

message.addRecipient(Message.RecipientType.CC, "abc@abc.example,abc@def.example,ghi@abc.example");

or message.addRecipient(Message.RecipientType.CC, “abc@abc.example;abc@def.example;ghi@abc.example”);

我也可以使用其他方法发送消息,但我想知道上述方法的目的。

如果我不能使用它(因为到目前为止我还没有得到上述要求的任何答案),那么这种方法在邮件API中有什么需要。


答案 1

如果多次调用,则会将给定的收件人添加到给定时间(TO、CCBCC)的收件人列表中。addRecipient

例如:

message.addRecipient(Message.RecipientType.CC, InternetAddress.parse("abc@abc.example"));
message.addRecipient(Message.RecipientType.CC, InternetAddress.parse("abc@def.example"));
message.addRecipient(Message.RecipientType.CC, InternetAddress.parse("ghi@abc.example"));

它会将这三个地址添加到 CC。


如果您希望一次添加所有地址,则应使用或并为其提供地址数组setRecipientsaddRecipients

Address[] cc = new Address[] {InternetAddress.parse("abc@abc.example"),
                               InternetAddress.parse("abc@def.example"),
                               InternetAddress.parse("ghi@abc.example")};
message.addRecipients(Message.RecipientType.CC, cc);

您还可以使用来解析地址列表:InternetAddress.parse

message.addRecipients(Message.RecipientType.CC,
                      InternetAddress.parse("abc@abc.example,abc@def.example,ghi@abc.example"));

答案 2

此代码适用于我。请尝试使用此功能向多个收件人发送邮件

private String recipient = "yamabs@gmail.com ,priya@gmail.com ";
String[] recipientList = recipient.split(",");
InternetAddress[] recipientAddress = new InternetAddress[recipientList.length];
int counter = 0;
for (String recipient : recipientList) {
    recipientAddress[counter] = new InternetAddress(recipient.trim());
    counter++;
}
message.setRecipients(Message.RecipientType.TO, recipientAddress);

推荐