Monday, September 14, 2009

Send Email from Java program using apache commons email

This api allows you to send email from your java progra. You can download the API from the folowing site
Download


Here I am giving you a sample code which lets you to send email fromyuor system

SimpleEmail email = new SimpleEmail();
email.setHostName("localhost");
try {
email.addTo("nimishth@gmail.com","Nimish T");
email.setFrom("admin@localhost");
email.setSubject("test");
email.setMsg("test message");
email.send();
} catch (EmailException e) {
e.printStackTrace();
}

first of all you have to include the downloaded library into u'r class path
after that write a java class and create an instarnce of SimpleEmail
then you have to set the set the host name, from address and to address
after that just add the message you want to send and and set a subject for the
perticular instance of the SimpleEmail class. here after you can call the sen method
which will send the email to the to address you have specified here its nimishth@gmail.com

If u want to send the mail using oter hservice providers such as gmail or oters
u have to change the the host name by the smtp address of the service provider you want to use
but there need authentication also
ie
SimpleEmail email = new SimpleEmail();
email.setHostName("smtp.gmail.com");
try {
email.addTo("nimishth@gmail.com","Nimish T");
email.setFrom("your email address");
email.setAuthentication("yoru email address", "your password");
email.setTLS(true);
//465 or 587 which is the port number here
email.setSmtpPort(587);
email.setSubject("Test");
email.setMsg("test");
email.send();
} catch (EmailException e) {
e.printStackTrace();
}

You will get more details about the mail such as attachment, html mail etc from
User Guide

No comments:

Post a Comment

LinkWithin

Related Posts with Thumbnails