Java多个抄送人发送邮件
时间: 2023-11-03 08:04:20 浏览: 51
可以使用JavaMail API来发送带有多个抄送人的邮件。以下是一个简单的示例代码:
```java
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class SendEmail {
public static void main(String[] args) {
// 收件人电子邮箱
String to = "recipient@example.com";
// 抄送人电子邮箱列表
String[] cc = {"cc1@example.com", "cc2@example.com"};
// 发件人电子邮箱
String from = "sender@example.com";
// 发件人电子邮箱密码
String password = "password";
// 指定发送邮件的主机为 smtp.gmail.com
String host = "smtp.gmail.com";
// 获取系统属性
Properties properties = System.getProperties();
// 设置邮件服务器
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.smtp.port", "587");
// 获取默认的 Session 对象
Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, password);
}
});
try {
// 创建默认的 MimeMessage 对象
MimeMessage message = new MimeMessage(session);
// 设置发件人
message.setFrom(new InternetAddress(from));
// 设置收件人
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// 设置抄送人
for (int i = 0; i < cc.length; i++) {
message.addRecipient(Message.RecipientType.CC, new InternetAddress(cc[i]));
}
// 设置邮件主题
message.setSubject("This is the Subject Line!");
// 设置邮件正文
message.setText("This is actual message");
// 发送邮件
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
```
在上面的示例中,我们使用了`message.addRecipient(Message.RecipientType.CC, new InternetAddress(cc[i]))`来添加多个抄送人。