JavaMail API supports the JavaMail (javax.mail) interface for sending email messages. It provides classes for sending email from remote smtp server with authentication like Gmail, sendgrid etc.
In this article we are using JavaMail API for sending emails using Java programming language through remote smtp server. This articles example are using Gmail smtp server as a remote smtp server for sending emails.
Step 1: Setup JavaMail Environment
First we need to download jar file containing all classes in javax.mail. Download jar (mail.jar) file from oracle official website.
Now set the classpath in system environment. Windows users make sure you have configured PATH variable for your Java installation.
c:> set classpath=mail.jar;.;
# export JAVA_HOME=/opt/jdk1.8.0_05/ # export PATH=$PATH:$JAVA_HOME/bin # export CLASSPATH=$JAVA_HOME/jre/lib/ext:$JAVA_HOME/lib/tools.jar:mail.jar:.
Step 2: Write a Java Program to Send Email
Create a java file SendMail.java with the following content. In this script you need to change many setting as per your setup. This script can be used for sending email through TLS or SSL SMTP connection through Gmail smtp servers.
Step 3: Execute Program to Send Email
Finally we need to execute java program to send email. as we know that this happens in two steps, first to compile program and second to run it.
# javac SendMail.java # java SendMail