Java 如何将相同的邮件发送给组中的每个收件人?
我正在尝试从我的jsf页面发送邮件。这是我的方法:Java 如何将相同的邮件发送给组中的每个收件人?,java,jsf,jakarta-mail,Java,Jsf,Jakarta Mail,我正在尝试从我的jsf页面发送邮件。这是我的方法: public String voegGroepToe() { String resultaat = "overzichtGroepEnProject"; if(project.getGroepen().size()<project.getMaxAantalGroepen()) project.voegGroepToe(groep); for(Student s : groep.ge
public String voegGroepToe()
{
String resultaat = "overzichtGroepEnProject";
if(project.getGroepen().size()<project.getMaxAantalGroepen())
project.voegGroepToe(groep);
for(Student s : groep.getStudenten())
{
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.live.com");
props.put("mail.smtp.port", "587");
Session mailSession = Session.getDefaultInstance(props);
Message simpleMessage = new MimeMessage(mailSession);
InternetAddress fromAddress = null;
InternetAddress toAddress = null;
try {
fromAddress = new InternetAddress(from);
toAddress = new InternetAddress(s.getEmail());
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
simpleMessage.setFrom(fromAddress);
simpleMessage.setRecipient(RecipientType.TO, toAddress);
simpleMessage.setSubject(subject);
simpleMessage.setText(message);
Transport.send(simpleMessage);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return resultaat;
}
公共字符串voegGroepToe()
{
字符串resultaat=“overzichtGroepEnProject”;
如果(project.getGroepen().size()您希望在循环之前只连接一次,然后在循环内部使用发送每条消息,然后在循环之后关闭连接。第二个问题是,您似乎没有在任何地方传入用户名/密码
以下是您应该如何做到这一点:
String host = "smtp.live.com";
int port = 587;
String username = "you@live.com";
String password = "yourpassword";
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", String.valueOf(port));
Session mailSession = Session.getDefaultInstance(props);
Transport transport = null;
try {
transport = mailSession.getTransport("smtp");
transport.connect(host, username, password);
InternetAddress fromAddress = new InternetAddress(from);
for (Student s : groep.getStudenten()) {
InternetAddress[] toAddresses = { new InternetAddress(s.getEmail()) };
Message simpleMessage = new MimeMessage(mailSession);
simpleMessage.setFrom(fromAddress);
simpleMessage.setRecipients(RecipientType.TO, toAddresses);
simpleMessage.setSubject(subject);
simpleMessage.setText(message);
simpleMessage.setSentDate(new Date()); // Otherwise you end up in junk.
simpleMessage.saveChanges(); // Transport#sendMessage() doesn't do it.
transport.sendMessage(simpleMessage, toAddresses);
}
} catch (MessagingException e) {
// Handle it! Display a FacesMessage or something.
} finally {
if (transport != null) try { transport.close(); } catch (MessagingException ignore) {}
}
(我不能保证它会以这种方式工作,我没有使用Live.com SMTP服务器的经验,也许您需要一个额外的身份验证程序
)
作为一种完全不同的选择,您还可以向groupname@yourdomain.com
将所有收件人作为密件抄送
另见:
请注意,这个问题与JSF完全无关。在使用main()
方法的普通Java类中执行此操作时,您会遇到完全相同的问题