Java Program to Send Mail


Introduction


This Program will help to send mail to others using Java Program. The Develop can use this  program to build an application or APP which can send notification when any action happened like task assignment, task removal, comment on task etc.

Please find program below –

 


Java Program


package com.kw.sample;

import javax.mail.*;

import javax.mail.internet.*;

import java.util.*;
import java.security.Security;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class KWMail

{

public static final void sendMail(String to, String title, String content) {
try {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", "smtp.gmail.com");
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.auth", "true");
final String username = "dknitk@gmail.com";
final String password = "PASSWORD";
Session session = Session.getDefaultInstance(props,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username,
password);
}
});

// -- Create a new message --
Message msg = new MimeMessage(session);

// -- Set the FROM and TO fields --
msg.setFrom(new InternetAddress(to));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(
to, false));
msg.setSubject(title);
msg.setText(content);
msg.setSentDate(new Date());
Transport.send(msg);

} catch (MessagingException e) {
//_log.error(e);
}

}
public static void main(String[] args){
sendMail("dknitk@rediffmail.com","Hello Test Mail","This is my Test to start one good project.");
}

}

 

Leave a Reply

Your email address will not be published. Required fields are marked *