How do I send an e-mail in Java?
JavaMail can be a bit of a pain to use. If you want a simpler, cleaner, solution then have a look at the Spring wrapper for JavaMail. The reference docs are here:
http://static.springframework.org/spring/docs/2.5.x/reference/mail.html
However, this does mean you need Spring in your application, if that isn't an option then you could look at another opensource wrapper such as simple-java-mail:
simplejavamail.org
Alternatively, you can use JavaMail directly, but the two solutions above are easier and cleaner ways to send email in Java.
Here's my code for doing that:
import javax.mail.*;
import javax.mail.internet.*;
// Set up the SMTP server.
java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.host", "smtp.myisp.com");
Session session = Session.getDefaultInstance(props, null);
// Construct the message
String to = "[email protected]";
String from = "[email protected]";
String subject = "Hello";
Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(from));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject(subject);
msg.setText("Hi,\n\nHow are you?");
// Send the message.
Transport.send(msg);
} catch (MessagingException e) {
// Error.
}
You can get the JavaMail libraries from Sun here: http://java.sun.com/products/javamail/