Tuesday, August 25, 2009

Send Mail Using JAVA MAIL API

The JavaMail API is a set of abstract APIs that model a mail system. The API provides a platform independent and protocol independent framework to build Java technology based email client applications. The JavaMail API provides facilities for reading and sending email. Service providers implement particular protocols. Several service providers are included with the JavaMail API package; others are available separately. The JavaMail API is implemented as a Java optional package that can be used on JDK 1.4 and later on any operating system. The JavaMail API is also a required part of the Java Platform, Enterprise Edition (Java EE).
You can download Java Mail API from http://java.sun.com/products/javamail/downloads/

An Example program for sending mail using JAVA Mail
------------------------------------------------------------------
Before run the example code please goes through steps given below

1. download java mail API. and add to Classpath
2. Create one Gmail Account ( in this example we use google mail server as server)
3. edit the code "USERNAME = new gmail id" and PASSWORD = "password of new gmail id";
4. edit formAddress and to address.

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


public class SendMail {

public static final String MAIL_SERVER = "smtp.gmail.com";
public static final String USERNAME = "servermail@gmail.com";
public static final String PASSWORD = "password";

public static void main(String[] args) {
try {
fromAddress = "fromaddress@gmail.com";
String toAddress = "toaddress@gmail.com";
String subject = "This is a test Message";
String message = "Hello Hows u?";

Properties properties = System.getProperties();
properties.put("mail.smtps.host", MAIL_SERVER);
properties.put("mail.smtps.auth", "true");

Session session = Session.getInstance(properties);
MimeMessage msg = new MimeMessage(session);

msg.setFrom(new InternetAddress(fromAddress));
msg.addRecipients(Message.RecipientType.TO, toAddress);
msg.setSubject(subject);
msg.setText(message);

Transport tr = session.getTransport("smtps");
tr.connect(MAIL_SERVER, USERNAME, PASSWORD);
tr.sendMessage(msg, msg.getAllRecipients());
tr.close();
} catch (AddressException ex) {
System.out.println(ex.getMessage());
} catch (MessagingException ex) {
System.out.println(ex.getMessage());
}
}
}

webdevelopers webhosting application development-IT solutions Cochin Kerala

2 comments:

LinkWithin

Related Posts with Thumbnails