How to add cc in mail using java
To add a CC (Carbon Copy) recipient in an email using Java, you can use the JavaMail API. Here's an example:
Step 1: Add the JavaMail API to your project
You can add the JavaMail API to your project using Maven or Gradle. Here's an example of how to add it using Maven:
<dependencies>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
</dependencies>
Step 2: Create a JavaMail session
Create a JavaMail session using the Session
class:
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
// Create a JavaMail session
Session session = Session.getDefaultInstance(new Properties(), null);
Step 3: Create a MimeMessage
Create a MimeMessage
object to represent the email:
MimeMessage message = new MimeMessage(session);
Step 4: Set the sender and recipient
Set the sender and recipient of the email:
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
Step 5: Add CC recipients
Add the CC recipients using the addRecipients
method:
message.addRecipients(Message.RecipientType.CC, new InternetAddress[] {
new InternetAddress("[email protected]"),
new InternetAddress("[email protected]")
});
Step 6: Set the subject and body
Set the subject and body of the email:
message.setSubject("Test email");
message.setText("This is a test email.");
Step 7: Send the email
Send the email using the Transport
class:
Transport.send(message);
Here's the complete code:
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendEmail {
public static void main(String[] args) {
// Create a JavaMail session
Session session = Session.getDefaultInstance(new Properties(), null);
// Create a MimeMessage
MimeMessage message = new MimeMessage(session);
// Set the sender and recipient
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
// Add CC recipients
message.addRecipients(Message.RecipientType.CC, new InternetAddress[] {
new InternetAddress("[email protected]"),
new InternetAddress("[email protected]")
});
// Set the subject and body
message.setSubject("Test email");
message.setText("This is a test email.");
// Send the email
Transport.send(message);
}
}
Note that you'll need to replace the placeholders ([email protected]
, [email protected]
, [email protected]
, [email protected]
) with the actual email addresses you want to use.