The JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications. The JavaMail API is available as an optional package for use with the Java SE platform and is also included in the Java EE platform.
This API gives Developers an easy, simplified and robust framework to write an Email Sender. It has very good integration with Spring Framework which has a ready to use Template to work with JavaMail. JavaMail with Spring is covered in a separate post which could be found under Spring Tab.
Following Example is self explanatory but if you have any question/query please leave a comment.
To run this program you will require javamail jar.
- You can download latest version of JavaMail (Version 1.5.1) from Java's standard website
package com.meritmix.blog.j2ee;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
* @author Ravi Yadav
* This is copyright content of MeritMix.com
* blog address is blog.meritmix.com
*/
public class MailSender {
public static void main(String[] args) {
new MailSender().sendMail();
}
public void sendMail() {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");// replace with your own smth host
props.put("mail.smtp.auth", "true");
//props.put("mail.debug", "true"); // uncomment this if you want to see log trace
props.put("mail.smtp.port", 25);// replace port
props.put("mail.smtp.socketFactory.port", 25);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.transport.protocol", "smtp");
Session mailSession = null;
mailSession = Session.getInstance(props,
new javax.mail.Authenticator() {
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication("username@gmail.com",
"Password");
}
});
try {
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
message.setSubject("Sample Subject");
message.setFrom(new InternetAddress("Sample@sample.com"));
String[] to = new String[] { "email@yahoo.co.in" };
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
to[0]));
String body = "Sample text";
//message.setSentDate(new Date());
//message.setText("Hello, world!\n"); //sets the given String as this part's content,
//with a MIME type of "text/plain".
message.setContent(body, "text/html");
transport.connect();
transport.sendMessage(message,
message.getRecipients(Message.RecipientType.TO));
transport.close();
} catch (Exception exception) {
}
}
}
No comments:
Post a Comment