javamail 配置多个邮箱进行发送 异常
时间: 2023-11-03 10:04:18 浏览: 44
要使用JavaMail发送多个邮箱,你需要创建多个Session对象,每个Session对象都需要单独的SMTP服务器、用户名和密码。以下是一个简单的示例代码,可以用来发送多个邮件:
```java
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class SendMail {
public static void main(String[] args) throws Exception {
// SMTP服务器地址和端口
String smtpServer = "smtp.gmail.com";
int smtpPort = 587;
// 发件人邮箱
String from = "your_email_address@gmail.com";
// 发件人邮箱密码
String password = "your_email_password";
// 收件人邮箱列表
List<String> toList = new ArrayList<String>();
toList.add("recipient1@example.com");
toList.add("recipient2@example.com");
toList.add("recipient3@example.com");
// 创建邮件会话
Properties props = new Properties();
props.put("mail.smtp.host", smtpServer);
props.put("mail.smtp.port", smtpPort);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, password);
}
});
// 发送邮件
for (String to : toList) {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject("Test Email");
message.setText("Hello World!");
Transport.send(message);
System.out.println("Mail sent to " + to);
}
}
}
```
在这个示例中,我们使用了一个for循环来遍历收件人邮箱列表,并为每个收件人创建了一个新的MimeMessage对象。然后,我们使用Transport.send()方法发送每个邮件。你可以根据需要修改收件人列表和邮件内容。