How to send an email using java.

In this example, I am gonna explain how to send an email using the java.
Flow
Here is my sample standalone java program
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Properties;
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;

/**
 *
 * @author javasnipets.info
   @Description:This class send a email to user.
 */
public class mail {

    public static void main(String[] args) throws UnknownHostException {
        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", "587");
        String from = "abc@mail.com";
        String password = "******";
        String to = "xyz@mail.com";
        String sub = "Greetngs From javasnippets";
        //InetAddress localhost = InetAddress.getLocalHost();
        //String msg = localhost.getHostAddress().trim();
        //get Session 
        String msg="Hello user this is the sample email from javasnippets team";  
        Session session = Session.getDefaultInstance(props,new javax.mail.Authenticator() 
        {
            protected PasswordAuthentication getPasswordAuthentication() 
            {
                return new PasswordAuthentication(from, password);
            }
        });
        //compose message    
        try {
            MimeMessage message = new MimeMessage(session);
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject(sub);
            message.setText(msg);
            //send message  
            Transport.send(message);
            System.out.println("message sent successfully");
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}
Explanation:
  1. First, create the properties instance. and add the all SMTP details Gmail.
  2. Here are the SMTP details of Gmail
  3. host:smtp.gmail.com
  4. port:587 Tcl secure connection port 465
  5. Use the PasswordAuthentication method to user given username and password is correct or not.
  6. Create the message instance and use the methods like addRecipient, subject,setText to add the receipts and subjects and message to mail. 
  7. Finally, use the transport. send method to send the mail to the user.
Output:
 Output