在Java中向两个不同的电子邮件地址发送两封电子邮件,可以使用JavaMail API来实现。下面是一个示例代码:
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 fromEmail = "sender@example.com";
String toEmail1 = "recipient1@example.com";
String toEmail2 = "recipient2@example.com";
// 邮件内容
String subject = "JavaMail Test";
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", "587");
// 创建会话对象
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// 创建邮件消息
Message message1 = new MimeMessage(session);
message1.setFrom(new InternetAddress(fromEmail));
message1.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail1));
message1.setSubject(subject);
message1.setText(body);
Message message2 = new MimeMessage(session);
message2.setFrom(new InternetAddress(fromEmail));
message2.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail2));
message2.setSubject(subject);
message2.setText(body);
// 发送邮件
Transport.send(message1);
Transport.send(message2);
System.out.println("Emails sent successfully.");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
上述代码使用JavaMail API连接到指定的邮件服务器,并创建两个邮件消息对象,分别设置发件人、收件人、主题和正文。然后通过Transport.send()
方法发送邮件。请注意替换示例中的邮件服务器配置、发件人和收件人信息为实际的值。
推荐的腾讯云相关产品:腾讯企业邮,详情请参考腾讯企业邮产品介绍。
领取专属 10元无门槛券
手把手带您无忧上云