用 Java 向多个收件人发送邮件

我要使用以下方法向多个收件人发送消息:

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

或者 AddRecipient (消息 recipienttype.cc : “ abc@abc.example; abc@def.example; ghi@abc.example”) ;

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

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

261314 次浏览

If you invoke addRecipient multiple times, it will add the given recipient to the list of recipients of the given time (TO, CC, and BCC).

For example:

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

It will add the three addresses to CC.


If you wish to add all addresses at once, you should use setRecipients or addRecipients and provide it with an array of addresses

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

You can also use InternetAddress.parse to parse a list of addresses:

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

You can have multiple addresses separated by comma

if (cc.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
else
message.setRecipient(Message.RecipientType.CC, new InternetAddress(cc));

You can use n number of recipients with the below method:

String to[] = {"a@gmail.com"} // Mail ID you want to send;
InternetAddress[] address = new InternetAddress[to.length];
for(int i=0; i< to.length; i++)
{
address[i] = new InternetAddress(to[i]);
}


msg.setRecipients(Message.RecipientType.TO, address);

So ... it took many months, but still ... You can send email to multiple recipients by using the ',' as separator and

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

is OK. At least in JavaMail 1.4.5

This code is working for me. Please try with this for sending mail to multiple recipients

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

Try this way:

message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("mail3@mail.example"));
String address = "mail@mail.example,mail2@mail.example";
InternetAddress[] iAdressArray = InternetAddress.parse(address);
message.setRecipients(Message.RecipientType.CC, iAdressArray);

InternetAddress.Parse is going to be your friend! See the worked example below:

String to = "med@joe.example, maz@frank.example, jezz@jam.example";
String toCommaAndSpaces = "med@joe.example maz@frank.example, jezz@jam.example";
  1. Parse a comma-separated list of email addresses. Be strict. Require comma separated list.

  2. If strict is true, many (but not all) of the RFC822 syntax rules for emails are enforced.

    msg.setRecipients(Message.RecipientType.CC,
    InternetAddress.parse(to, true));
    
  3. Parse comma/space-separated list. Cut some slack. We allow spaces seperated list as well, plus invalid email formats.

    msg.setRecipients(Message.RecipientType.BCC,
    InternetAddress.parse(toCommaAndSpaces, false));
    

If you want to send as CC using MimeMessageHelper:

List<String> emails = new ArrayList();
email.add("email1");
email.add("email2");


for (String string : emails) {
message.addCc(string);
}

In the same way, you can use to add multiple recipients.

Just use the method message.setRecipients with multiple addresses separated by commas:

message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("abc@abc.example,abc@def.com,ghi@abc.example"));


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

It works fine with only one address too:

message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("abc@abc.example"));
String[] mailAddressTo = new String[3];
mailAddressTo[0] = emailId_1;
mailAddressTo[1] = emailId_2;
mailAddressTo[2] = "xyz@gmail.com";


InternetAddress[] mailAddress_TO = new InternetAddress[mailAddressTo.length];


for (int i = 0; i < mailAddressTo.length; i++)
{
mailAddress_TO[i] = new InternetAddress(mailAddressTo[i]);
}


message.addRecipients(Message.RecipientType.TO, mailAddress_TO);ress_TO = new InternetAddress[mailAddressTo.length];

Internet E-mail address format (RFC 822):

(,)comma separated sequence of addresses

javax.mail - 1.4.7 parse(String[]) is not allowed. So we have to give a comma-separated sequence of addresses into InternetAddress objects. Addresses must follow the RFC822 syntax.

String toAddress = "mail@mail.example,mail2@mail.example";
InternetAddress.parse(toAddress);

(;) semi-colon separated sequence of addresses « If a group of address list is provided with delimiter as ";", then convert to a string array using the split method to use the following function.

String[] addressList = { "mail@mail.example", "mail2@mail.example" };


String toGroup = "mail@mail.example;mail2@mail.example";
String[] addressList2 = toGroup.split(";");


setRecipients(message, addressList);
public static void setRecipients(Message message, Object addresslist) throws AddressException, MessagingException {
if (addresslist instanceof String) { // CharSequence
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse((String) addresslist));
} else if (addresslist instanceof String[]) { // String[] « Array with collection of Strings/
String[] toAddressList = (String[]) addresslist;
InternetAddress[] mailAddress_TO = new InternetAddress[ toAddressList.length ];
for (int i = 0; i < toAddressList.length; i++) {
mailAddress_TO[i] = new InternetAddress(toAddressList[i]);
}
message.setRecipients(Message.RecipientType.TO, mailAddress_TO);
}
}

Full example

public static Properties getMailProperties(boolean addExteraProps) {
Properties props = new Properties();
props.put("mail.transport.protocol", MAIL_TRNSPORT_PROTOCOL);
props.put("mail.smtp.host", MAIL_SERVER_NAME);
props.put("mail.smtp.port", MAIL_PORT);


// Sending Email to the GMail SMTP server requires authentication and SSL.
props.put("mail.smtp.auth", true);
if(ENCRYPTION_METHOD.equals("STARTTLS")) {
props.put("mail.smtp.starttls.enable", true);
props.put("mail.smtp.socketFactory.port", SMTP_STARTTLS_PORT); // 587
} else {
props.put("mail.smtps.ssl.enable", true);
props.put("mail.smtp.socketFactory.port", SMTP_SSL_PORT); // 465
}
props.put("mail.smtp.socketFactory", SOCKETFACTORY_CLASS);
return props;
}


public static boolean sendMail(String subject, String contentType, String msg, Object recipients) throws Exception {


Properties props = getMailProperties(false);
Session mailSession = Session.getInstance(props, null);
mailSession.setDebug(true);


Message message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(USER_NAME));


setRecipients(message, recipients);


message.setSubject(subject);


String htmlData = "<h1>This is actual message embedded in HTML tags</h1>";
message.setContent(htmlData, "text/html");


Transport transport = mailSession.getTransport(MAIL_TRNSPORT_PROTOCOL);
transport.connect(MAIL_SERVER_NAME, Integer.valueOf(MAIL_PORT), USER_NAME, PASSWORD);
message.saveChanges(); // Don't forget this


transport.sendMessage(message, message.getAllRecipients());
transport.close();
}

Using Appache SimpleEmail - commons-email-1.3.1

Example: email.addTo(addressList);

public static void sendSimpleMail() throws Exception {
Email email = new SimpleEmail();
email.setSmtpPort(587);


DefaultAuthenticator defaultAuthenticator = new DefaultAuthenticator(USER_NAME, PASSWORD);


email.setAuthenticator(defaultAuthenticator);
email.setDebug(false);
email.setHostName(MAIL_SERVER_NAME);
email.setFrom(USER_NAME);
email.setSubject("Hi");
email.setMsg("This is a test mail... :-)");


//email.addTo("mail@mail.example", "Yash");
String[] toAddressList = { "mail@mail.example", "mail2@mail.example" }
email.addTo(addressList);


email.setTLS(true);
email.setStartTLSEnabled(true);
email.send();
System.out.println("Mail sent!");
}

An easy way to do it:

String[] listofIDS = {"ramasamygms@gmail.com", "ramasamycse94@gmail.com"};
        

for(String cc:listofIDS) {
message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
}