add cc and bcc in the address while sending the mail using java
Stefan Bogdanescu
Founder & Senior Architect
Mastering Email Sending in Java: Adding CC and BCC Recipients
Sending emails programmatically using JavaMail provides immense flexibility for building custom notification systems or backend services. When you are sending an email via Java, a common requirement is to manage not just the primary recipient (TO) but also the copied (CC) and blind carbon copy (BCC) recipients.
The issue you are facing stems from how the MimeMessage object handles different types of recipients. While your current code correctly sets the primary recipient using setRecipients(Message.RecipientType.TO, ...), adding CC and BCC requires explicitly defining these separate recipient groups.
As a senior developer, understanding the nuances of the JavaMail API is crucial for robust communication systems. Let's dive into how you can successfully implement CC and BCC functionality in your Java email sending process.
Understanding Message Recipients in JavaMail
The javax.mail package provides methods to manipulate the structure of an email message before it is sent via the SMTP server. To handle multiple recipients correctly, we must utilize the Message.RecipientType enumeration.
The key to solving your problem lies in using three distinct calls within the MimeMessage object: one for the primary recipient (TO), one for the carbon copies (CC), and one for the blind copies (BCC).
The Solution: Implementing CC and BCC
To send an email with TO, CC, and BCC addresses, you need to use setRecipients() three times, specifying the correct type for each list of emails.
Here is the corrected and enhanced implementation demonstrating how to include all three types of recipients in your Java code:
import javax.mail.*;
import javax.mail.internet.*;
import java.util.List;
public class EmailSender {
public String sendEmail(String toEmail, String ccEmail, String bccEmail, String body) {
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);
// 1. Set the sender (From)
message.setFrom(new InternetAddress(username));
// 2. Set the primary recipient (To)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
// 3. Set the Carbon Copy recipients (CC)
if (ccEmail != null && !ccEmail.isEmpty()) {
message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail));
}
// 4. Set the Blind Carbon Copy recipients (BCC)
if (bccEmail != null && !bccEmail.isEmpty()) {
message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bccEmail));
}
message.setSubject("Important Notification");
message.setText(body);
Transport.send(message);
return "Y"; // Success
} catch (MessagingException e) {
e.printStackTrace();
return "N"; // Failure
}
}
}
Detailed Explanation of Changes
Separate Recipient Types: Instead of focusing only on
Message.RecipientType.TO, we now explicitly use:Message.RecipientType.TO: For the primary recipient(s).Message.RecipientType.CC: For recipients who should be copied (visible to all recipients).Message.RecipientType.BCC: For recipients whose addresses should remain hidden from other recipients.
Handling Nulls: I have added basic null and empty checks (
if (ccEmail != null && !ccEmail.isEmpty())) before attempting to parse the address. This is a crucial best practice to preventNullPointerExceptionorMessagingExceptionif you are sending an email without a specific CC or BCC address provided.
Architectural Context: Java vs. PHP Frameworks
While mastering low-level APIs like JavaMail is powerful, it's important to understand the context of modern application development. In environments like PHP, developers often leverage robust frameworks that abstract away these complex details. For instance, when building an application around services where backend logic needs to interact with external APIs—whether it's sending transactional emails or managing data—understanding how systems handle asynchronous operations and external service interactions is key. Frameworks like Laravel provide elegant solutions for many tasks, allowing developers to focus more on business logic rather than intricate API configurations.
Conclusion
Adding CC and BCC functionality in JavaMail is achieved by utilizing the distinct RecipientType settings within the MimeMessage object. By correctly setting separate lists for TO, CC, and BCC addresses, you ensure that your email delivery adheres to standard communication protocols. Always employ defensive coding practices, such as checking for null inputs, to make your email sending utility resilient against unexpected data.