Saturday, July 23, 2011

Java Send e-mail

In this post, by using JavaMail API, I will write a java program that sends an e-mail to the given e-mail address.
The JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging application.
Download the library and add it to your class path. Then start your development environment and use this code to send e-mail.


final String sender = “sender@gmail.com”;
final String password = “yourpassword”;
final String receiver = “receiver@gmail.com”;
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.debug", "true");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(sender, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(sender));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver));
message.setSubject(subject);
message.setText(body);

Transport.send(message);
System.out.println("Email was Sent!!");
} catch (MessagingException e) {
throw new RuntimeException(e);
}


Change the values according to your accounts. For example change sender and receiver values.
I wish to be useful.