Send Mail to multiple Recipients in java

Prateek picture Prateek · Dec 13, 2012 · Viewed 221k times · Source

I want to send a message to multiple Recipients using following the method :

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

OR

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

But one confusion is that in second arguement, how to pass multiple addresses like :

message.addRecipient(Message.RecipientType.CC, "[email protected],[email protected],[email protected]");

OR

message.addRecipient(Message.RecipientType.CC, "[email protected];[email protected];[email protected]");

I can send a message using alternate methods too, but want to know the purpose of the above method. If I cant use it(as till now i haven't got any answer for above requirement) then what is the need for this method to be in mail API.

Answer

Aviram Segal picture Aviram Segal · Dec 13, 2012

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

For example:

message.addRecipient(Message.RecipientType.CC, InternetAddress.parse("[email protected]"));
message.addRecipient(Message.RecipientType.CC, InternetAddress.parse("[email protected]"));
message.addRecipient(Message.RecipientType.CC, InternetAddress.parse("[email protected]"));

Will add the 3 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("[email protected]"),
                               InternetAddress.parse("[email protected]"), 
                               InternetAddress.parse("[email protected]")};
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("[email protected],[email protected],[email protected]"));