Java多个企业邮箱账号发送邮件
时间: 2023-11-03 19:04:36 浏览: 93
Java发送邮件给多人
要在Java中发送多个企业邮箱账号的邮件,您需要使用JavaMail API。
以下是一个基本的JavaMail示例代码:
```java
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class SendEmail {
public static void main(String[] args) {
// 配置邮件发送的SMTP服务器和端口
String host = "smtp.example.com";
int port = 587;
// 配置发送邮件账户的用户名和密码
String username = "example@example.com";
String password = "password";
// 配置邮件发送的收件人列表
String[] recipients = {"recipient1@example.com", "recipient2@example.com", "recipient3@example.com"};
// 配置邮件发送的主题和内容
String subject = "Test Email";
String body = "This is a test email sent from Java.";
// 创建邮件会话
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// 创建邮件消息
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
for (String recipient : recipients) {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
}
message.setSubject(subject);
message.setText(body);
// 发送邮件
Transport.send(message);
System.out.println("Email sent successfully.");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
```
在上面的示例代码中,将收件人列表设置为一个字符串数组。您可以通过将多个收件人的邮件地址添加到该数组中来发送邮件给多个收件人。
阅读全文