Monday, April 13, 2009

JAVA: send emails through a console application

ive searched a lot for help on sending emails through an application. But i found most of the articles on the web very confusing, i think this java application is one of the most simplest solution from which i could come up with the console application to send email. This java application can send emails through a console application.

i have referred many articles before writing this post, the credit goes to the concerned programmers article/blog to which ive referred


You read the code and use it accordingly . Understand the code and u can integrate this into a JSP page or a desktop application combining with appropriate JAVA API.

This code sends emails from your gmail account to the recipents from a console application.

before executing this code, download the mail.jar file from the
JAVAMAIL API
WEbsite.
and also the activation.jar file from java beans activiation framework website

and include them in the class path, otherwise you would get an class not found error


go through the code and make appropriate changes, to make it compatible with
other email service providers by referring to the following link
List of email service providers with smtp, pop configurations

JAVA CONSOLE APPLICATION TO SEND EMAIL FROM A GMAIL ACCOUNT



import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;


public class SimpleGmailSend {

private static final String SMTPHOST_NAME
= "smtp.gmail.com";

private static final int SMTPHOST_PORT = 465;
// 465 is for GMAIL.

private static final String SMTPAUTH_USER
="your email(like blah_blah@gmail.com)";

private static final String SMTPAUTH_PWD
= "your password";

public static void main(String[] args)
throws Exception{
new SimpleGmailSend().test();
}

public void test() throws Exception{
Properties props = new Properties();

props.put("mail.transport.protocol", "smtps");
props.put("mail.smtps.host", SMTPHOST_NAME);
props.put("mail.smtps.auth", "true");
// props.put("mail.smtps.quitwait", "false");

Session mailSession =
Session.getDefaultInstance(props);
mailSession.setDebug(true);
Transport transport = mailSession.getTransport();

MimeMessage message1 = new MimeMessage(mailSession);

message1.setSubject("Testing sending mails
through java application with GMAIL ");

message1.setContent("Your text in EMAIL GOES HERE",
"text/plain");
// add your text message above
// u can also write a swings application
//to read the email body and save it here

message1.addRecipient(Message.RecipientType.TO,
new InternetAddress
("toemail address(like blah@blah.com)"));


transport.connect(SMTPHOST_NAME, SMTPHOST_PORT,
SMTPAUTH_USER, SMTPAUTH_PWD);

transport.sendMessage(message1,
message1.getRecipients(Message.RecipientType.TO));
transport.close();
}
}

2 comments:

  1. Nice post my dear friend.....helped in my project
    thanx alot

    ReplyDelete