Java Email Message set BCC recipients

Description

Java Email Message set BCC recipients

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Main {
   public static void main(String[] args) {

      List<String> emails = getEmails();
      Properties properties = new Properties();
      properties.put("mail.smtp.host", "smtp.somewhere.com");
      properties.put("mail.smtp.auth", "true");

      Session session = Session.getDefaultInstance(properties, new MessageAuthenticator("username", "password"));

      Message message = new MimeMessage(session);
      try {//w ww .j  a  v a 2s . c o  m
         message.setFrom(new InternetAddress("someone@somewhere.com"));
         message.setRecipients(Message.RecipientType.BCC, getRecipients(emails));
         message.setSubject("Subject");
         message.setContent("This is a test message", "text/plain");
         Transport.send(message);
      } catch (MessagingException e) {
         e.printStackTrace();
      }
   }

   private static Address[] getRecipients(List<String> emails) throws AddressException {
      Address[] addresses = new Address[emails.size()];
      for (int i = 0; i < emails.size(); i++) {
         addresses[i] = new InternetAddress(emails.get(i));
      }
      return addresses;
   }

   public static List<String> getEmails() {
      ArrayList<String> emails = new ArrayList<>();
      emails.add("css@example.com");
      emails.add("html@example.com");
      emails.add("java@example.com");
      return emails;
   }

}

class MessageAuthenticator extends Authenticator {
   PasswordAuthentication authentication = null;

   public MessageAuthenticator(String username, String password) {
      authentication = new PasswordAuthentication(username, password);
   }

   @Override
   protected PasswordAuthentication getPasswordAuthentication() {
      return authentication;
   }
}



PreviousNext

Related