TheMightyLlama
TheMightyLlama

Reputation: 1273

Sending email to BCC recipients using javax.mail

I've got the below piece of code, but I can't figure out how to add the BCC recipients to the sendMessage.

Any ideas?

           MimeMessage message = new MimeMessage(mailSession);

      String today = new SimpleDateFormat("yyyy-MM-dd").format(Calendar
              .getInstance().getTime());

      message.setSubject("This is my email for:" + today);
      message.setFrom(new InternetAddress("[email protected]"));
      String []to = new String []{"[email protected]"};
      String []bcc = new String[]{"[email protected]","[email protected]","[email protected]"};
      message.addRecipient(Message.RecipientType.TO, new InternetAddress(to[0]));
      message.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc[0]));
      message.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc[1]));
      message.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc[2]));
      String body = theBody;
      message.setContent(body,"text/html");
      transport.connect();

        transport.sendMessage(message,message.getRecipients(Message.RecipientType.TO));
        transport.close();

Upvotes: 1

Views: 4512

Answers (2)

Anand Babu
Anand Babu

Reputation: 1

        String [] to=new String[3];
        to[0]="[email protected]";
        to[1]="[email protected]";
        to[2]="[email protected]";
        InternetAddress[] toAddress = new InternetAddress[to.length];

        // To get the array of addresses
        for( int i = 0; i < to.length; i++ ) {
            toAddress[i] = new InternetAddress(to[i]);
        }

        for( int i = 0; i < toAddress.length; i++) {
            message.addRecipient(Message.RecipientType.TO, toAddress[i]);

        }


        message.setSubject("Testing ");
        message.setText("dddd,"
            + "\n\n No spam to my email, please!");

        Transport.send(message);

Upvotes: 0

Pratik Shelar
Pratik Shelar

Reputation: 3212

You need to use the following method to add multiple reciepient

public void  addRecipients(Message.RecipientType type, Address[] addresses)

Also instead of the following line

transport.sendMessage(message,message.getRecipients(Message.RecipientType.TO));

Try this

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

Upvotes: 6

Related Questions