我正试图从我的jsf页面发送邮件。这是我的方法:
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;
}
resultaat是应用程序发送电子邮件后应该访问的JSF页面。Groep指的是一群学生。这封邮件应该发给小组的每个学生。from = "myownemailadress@hotmail.com"
但是这是不工作的,它没有给出一个错误消息,它看起来像是卡在Transport.send…我做错了什么?
您希望在循环之前仅连接一次,然后在循环内使用Transport#sendMessage()
发送每个消息,然后在循环之后关闭连接。第二个问题是,您似乎没有在任何地方传递用户名/密码。
你应该这样做:
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服务器的经验,也许你需要一个额外的Authenticator
)
作为一个完全不同的选择,你也可以发送一个消息给groupname@yourdomain.com
与所有这些收件人作为密件。
参见:
- JavaMail Fundamentals - Transport
请注意,这个问题与JSF完全无关。在使用main()
方法的普通Java类中这样做时,您将遇到完全相同的问题。