Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java adding CC and BCC to send email program

Tags:

java

email

I have the following codes, which is able to send mail from gmail. Question is at which part should I add the CC and BCC receiver so that they too can receive the mail.

I did a search and found some help here but it doesnt work on my program, i get error on the BCC and CC list.

    InternetAddress[] myToList = InternetAddress.parse("[email protected],[email protected]"); 
    InternetAddress[] myBccList = InternetAddress.parse("[email protected]"); 
    InternetAddress[] myCcList = InternetAddress.parse("[email protected]"); 


    message.setRecipients(Message.RecipientType.TO,myToList); 
    message.addRecipient(Message.RecipientType.BCC,myBccList); 
    message.addRecipient(Message.RecipientType.CC,myCcList);

Code

 import javax.mail.*;
    import javax.mail.internet.*;
    import java.util.*;
    
    public class SendEmail {
    
        private static final String SMTP_HOST_NAME = "smtp.gmail.com";
        private static final int SMTP_HOST_PORT = 587;
        private static final String SMTP_AUTH_USER = "[email protected]";
        private static final String SMTP_AUTH_PWD = "";
    
        public static void main(String[] args) throws Exception {
            SendEmail se = new SendEmail();
            se.mail();
        }
    
        public void mail() throws Exception {
            Properties props = new Properties();
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465");
    
            Session mailSession = Session.getDefaultInstance(props);
            mailSession.setDebug(true);
            Transport transport = mailSession.getTransport();
            MimeMessage message = new MimeMessage(mailSession);
            message.setSubject("Testing SMTP From Java");
    
            message.setContent("Hello world", "text/plain");
    
            message.addRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
    
            transport.connect(SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD);
            transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
            transport.close();
        }
    }
like image 606
searchfunction Avatar asked Dec 01 '25 04:12

searchfunction


1 Answers

Change:

message.setRecipients(Message.RecipientType.TO,myToList); 

to:

message.addRecipients(Message.RecipientType.TO,myToList);

and then:

transport.sendMessage(message, message.getAllRecipients());
like image 134
Nir Alfasi Avatar answered Dec 02 '25 18:12

Nir Alfasi