Java Mail with To, CC and BCC

42.1k views Asked by At

I am trying to send mail with to, cc and bcc. I am using javax.mail for achieving this. Please find below a part of my code

InternetAddress[] myToList = InternetAddress.parse("[email protected],[email protected]");
InternetAddress[] myBccList = InternetAddress.parse("[email protected]");
InternetAddress[] myCcList = InternetAddress.parse("[email protected]");
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(objEmail.getFrom()));
message.setRecipients(Message.RecipientType.TO,myToList);
message.setRecipients(Message.RecipientType.BCC,myBccList);
message.setRecipients(Message.RecipientType.CC,myCcList);

But when I try to execute this code, I am getting the below exception:

javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 452 4.5.3 Too many recipients

2

There are 2 answers

3
muthukumar On

Try this

InternetAddress[] myToList = InternetAddress.parse("[email protected],[email protected]");
InternetAddress[] myBccList = InternetAddress.parse("[email protected]");
InternetAddress[] myCcList = InternetAddress.parse("[email protected]");
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(objEmail.getFrom()));
message.setRecipients(Message.RecipientType.TO,myToList);
// changes,...
message.addRecipient(Message.RecipientType.BCC,myBccList);
message.addRecipient(Message.RecipientType.CC,myCcList);
0
said_dev On
InternetAddress[] toAddress = new InternetAddress[to.length];

        // To get the array of toaddresses
        for( int i = 0; i < to.length; i++ ) {
            toAddress[i] = new InternetAddress(to[i]);
            message.addRecipient(Message.RecipientType.TO, toAddress[i]);
        }

        InternetAddress[] ccAddress = new InternetAddress[cc.length];

        // To get the array of ccaddresses
        for( int i = 0; i < cc.length; i++ ) {
            ccAddress[i] = new InternetAddress(cc[i]);
            message.addRecipient(Message.RecipientType.CC, ccAddress[i]);
        }

        InternetAddress[] bccAddress = new InternetAddress[bcc.length];

        // To get the array of bccaddresses
        for( int i = 0; i < bcc.length; i++ ) {
            bccAddress[i] = new InternetAddress(bcc[i]);
            message.addRecipient(Message.RecipientType.BCC, bccAddress[i]);
        }

The not us .setRecipients if you need use CC or BCC