JAVA配置群发邮件
时间: 2024-04-13 12:21:33 浏览: 58
以下是JAVA配置群发邮件的示例:
1. 使用JavaMail实现群发邮件
```java
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendEmail {
public static void main(String[] args) {
String host = "smtp.example.com";
String username = "username";
String password = "password";
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@example.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to1@example.com, to2@example.com"));
message.setSubject("Group Email");
message.setText("This is a group email.");
Transport.send(message);
System.out.println("Group email sent successfully.");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
```
2. 使用Spring Mail框架实现群发邮件
```java
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
public class SendGroupEmail {
public static void main(String[] args) {
JavaMailSender mailSender = new JavaMailSenderImpl();
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("from@example.com");
message.setTo("to1@example.com", "to2@example.com");
message.setSubject("Group Email");
message.setText("This is a group email.");
mailSender.send(message);
System.out.println("Group email sent successfully.");
}
}
```
阅读全文