How do I send an e-mail 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/

Leave a Comment