Search code examples
javajakarta-mail

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("thesender@gmail.com"));
      String []to = new String []{"therecipient1@gmail.com"};
      String []bcc = new String[]{"therecipient2@gmail.com","therecipient3@gmail.com","therecipient4@gmail.com"};
      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();

Solution

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