Add cc and bcc to address when sending mail using java

I am sending an email using java. I want to send mail as an option bcc and cc also to the address as possible. I am using the following code.

public String sendemail(String xtomail,String xsub,String xbody) { final String username =" adeshsingh86@gmail.com "; final String password ="passwordhere"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected javax.mail.PasswordAuthentication getPasswordAuthentication() { return new javax.mail.PasswordAuthentication(username, password); } }); try { Message message = new MimeMessage(session); //message.setFrom(new InternetAddress(" adeshsingh86@gmail.com ")); message.setFrom(new InternetAddress(username)); message.setRecipients(Message.RecipientType.TO, //InternetAddress.parse(" kmukesh2008@gmail.com ")); InternetAddress.parse(xtomail)); //message.setSubject("Testing Subject"); message.setSubject(xsub); // message.setText("Dear Mail Crawler," // + "\n\n No spam to my email, please!"); message.setText(xbody); Transport.send(message); return "Y"; } catch (MessagingException e) { return "N"; //throw new RuntimeException(e); } } 
+4
source share
1 answer

You assign recipients to the setter method. See how you add it, you will see that you have added Message.RecipientType.TO. The same can be done with CC and BCC. You can also use the addRecipient method to do this.

Example:

 message.addRecipient(RecipientType.BCC, new InternetAddress( " your@email.com ")); message.addRecipient(RecipientType.CC, new InternetAddress( " yourOther@email.com ")); 

Additional Information: MimeMessage API

+18
source

Source: https://habr.com/ru/post/1469419/


All Articles