Java实现大批量邮件发送
时间: 2023-11-13 14:39:50 浏览: 39
要实现大批量邮件发送,可以使用 JavaMail API 来发送邮件。下面是一个简单的示例代码:
```java
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class EmailSender {
public static void main(String[] args) {
// 邮件服务器配置
String host = "smtp.example.com";
String username = "your_username";
String password = "your_password";
// 收件人列表
String[] recipients = {"recipient1@example.com", "recipient2@example.com"};
// 发件人
String from = "your_email@example.com";
// 邮件主题
String subject = "Hello from JavaMail";
// 邮件内容
String body = "This is a test email.";
// 邮件配置
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", "587");
// 创建会话
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// 创建邮件消息
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
for (String recipient : recipients) {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
}
message.setSubject(subject);
message.setText(body);
// 发送邮件
Transport.send(message);
System.out.println("Emails sent successfully!");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
```
请注意替换代码中的邮件服务器配置、发件人、收件人、用户名和密码等信息。这个示例代码只能发送纯文本邮件,如果需要发送带附件的邮件,可以参考 JavaMail API 的文档进行扩展。