java mail 三个_JavaMail - 多个发件人
时间: 2023-06-16 13:05:26 浏览: 150
JavaMail 是用于发送和接收电子邮件的 Java API。可以使用 JavaMail API 从多个发件人发送电子邮件,下面是一个示例:
```java
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MultipleSenders {
public static void main(String[] args) {
// 发件人列表
String[] fromList = {"[email protected]", "[email protected]"};
// 收件人
String to = "[email protected]";
// SMTP 服务器地址
String host = "smtp.example.com";
// 邮件标题
String subject = "JavaMail Test";
// 邮件内容
String text = "This is a test email from JavaMail.";
// 发件人用户名和密码
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 javax.mail.Authenticator() {
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication(username, password);
}
});
try {
// 创建邮件消息
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromList[0]));
for (int i = 1; i < fromList.length; i++) {
message.addFrom(InternetAddress.parse(fromList[i]));
}
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(subject);
message.setText(text);
// 发送邮件
Transport.send(message);
System.out.println("Email sent successfully.");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
```
在上面的示例中,我们使用 `addFrom()` 方法将多个发件人添加到邮件消息中。注意,SMTP 服务器可能会对此进行限制,因此请确保您遵守 SMTP 服务器的规定。另外,也要确保您有权使用添加的所有发件人地址。
阅读全文
相关推荐


















