Wednesday, August 12, 2009

Sending e-mail using JavaMail API

The JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications. The JavaMail API is implemented as a Java platform optional package and is also available as part of the Java platform, Enterprise Edition.

You can use the following code to send a textual e-mail message to a single recipient from your Java program. Note that you need to download JavaMail API and put required jars into your classpath to be able to run this program.

import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendApp {

public static void send(String smtpHost, int smtpPort,
String from, String to,
String subject, String content)
throws AddressException, MessagingException {

// Create a mail session
java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.port", ""+smtpPort);
Session session = Session.getDefaultInstance(props, null);

// Construct the message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject(subject);
msg.setText(content);

// Send the message
Transport.send(msg);
}

public static void main(String[] args) throws Exception {
// Send a test message
send("hostname", 25, " xxx@xyz.com ", " xyz@abc.com",
"Hello", "Hello, \n\n How are you ?");
}
}

No comments:

Post a Comment