95

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 the second argument, how to pass multiple addresses like:

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

I can send a message using alternate methods too, but I want to know the purpose of the above method.

If I can’t 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.

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
Prateek
  • 12,014
  • 12
  • 60
  • 81
  • Way too many of the answers are "try this" answers without any explanation (e.g., missing the intent (the thinking behind it), the gist, limitations, system tested on (incl. versions), etc.) and they have very little value. What if they don't work for some reason (e.g., due to version dependencies or a particular context)? If you are going to add a new answer, please don't just dump some code without explanation. Thanks in advance. – Peter Mortensen May 21 '22 at 20:18
  • [The Help Center says](https://stackoverflow.com/help/promotion): *"...always explain why the solution you're presenting is appropriate and how it works"*. – Peter Mortensen May 21 '22 at 20:19

12 Answers12

129

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"));
Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
Aviram Segal
  • 10,962
  • 3
  • 39
  • 52
  • So i have to use it n times for n recipients than what is the use of tis overloaded method....then second arguement as an Array is better.please suggest – Prateek Dec 13 '12 at 06:26
  • 1
    Actually my question is specifically regarding a particular method. – Prateek Dec 13 '12 at 06:42
  • 2
    you either use `addRecipient`/`setRecipient` with a single address or `addRecipients`/`setRecipients` with an array of addresses – Aviram Segal Dec 13 '12 at 06:53
  • please see docs of MimeMessage class there u find the method specified in my question. i want to know how to use that method – Prateek Dec 13 '12 at 07:02
  • Is this what you wanted ? parse the comma separated list of addresses ? – Aviram Segal Dec 13 '12 at 07:06
  • again your answer is missing the same thing,see the api u used dear. i searchrd a lot but till yet not get the answer – Prateek Dec 13 '12 at 07:07
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/21052/discussion-between-aviram-segal-and-prateek) – Aviram Segal Dec 13 '12 at 07:08
  • 3
    `javax.mail` version 1.5.5 doesn't have `InternetAddress.parse()` that returns `String`. All parse methods return array and so are not suitable for `addRecipient`. Is there other version (s) that has such method? – Yuriy N. Jan 16 '17 at 08:42
  • 3
    When you have `javax.mail` version `1.5.5` or greater where you don't have `InternetAddress.parse()` that returns single `InternetAddress` but only the one that returns `InternetAddress[]` (array) you can use the **the first solution** having `... message.addRecipient(Message.RecipientType.CC, InternetAddress.parse("abc@def.com")[0]); ...` **([0] is important there)**. In **the second solution:** `... new Address[] {InternetAddress.parse("abc@abc.com")[0], ...` **The third solution** should work without changes. Of course **[0]** at the end should be applied to all addresses in each solution. – luke Jun 22 '17 at 11:03
  • 1
    @luke.. thanks, I have been struggling for a while.. and your comment helped me. – stack0114106 Aug 09 '19 at 10:42
  • Instead of Message.RecipientType.CC use javax.mail.Message.RecipientType.CC – Sheshan Gamage Feb 14 '22 at 08:11
29

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);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
G.K
  • 299
  • 3
  • 3
18

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"));
Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
Leyo
  • 181
  • 1
  • 2
11

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));
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
ThePCWizard
  • 3,338
  • 2
  • 21
  • 32
  • 1
    Why wouldn't you use `InternetAddress.parse()` for both? (And yes, I know this is 4 years old) – Sean Bright Sep 08 '16 at 11:34
  • 2
    @seanbright yes you can just have the first statement skipping the if else condition altogether. `setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));` should work even if there's only 1 address. It's a just a personal way of programming to increase readability. – ThePCWizard Sep 08 '16 at 11:50
11

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);
Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
user3734721
  • 119
  • 1
  • 4
7

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!");
}
Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
Yash
  • 9,250
  • 2
  • 69
  • 74
6

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

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
bes67
  • 223
  • 1
  • 3
  • 8
6

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));
    
Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
Matt
  • 1,167
  • 1
  • 15
  • 26
3
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]; 
nick_w
  • 14,758
  • 3
  • 51
  • 71
2

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));
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ramasamy
  • 125
  • 2
  • 11
1

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);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dhinakar
  • 4,061
  • 6
  • 36
  • 68
1

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Arun
  • 41
  • 4