JavaMail API supports the JavaMail (javax.mail) interface for sending email messages. javax.mail has all the required classes for sending emails an other mail protocols like SMTP, POP3, and IMAP.
In this article we are using JavaMail API for sending emails using Java programming language through local smtp server. make sure you are running smtp server on localhost.
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.
Windows:
c:> set classpath=mail.jar;.;
Linux:
# 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 SendMailJavaAPI.java with the following content. In this script you need to change email to and from variable as per your requirements.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendMailJavaAPI { public static void main(String[] args) throws Exception{ String to="recipient@example.com"; String from="sender@example.com"; Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); String msgBody = "Sending email using JavaMail API..."; try { Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from, "NoReply")); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to, "Mr. Recipient")); msg.setSubject("Welcome To Java Mail API"); msg.setText(msgBody); Transport.send(msg); System.out.println("Email sent successfully..."); } catch (AddressException e) { throw new RuntimeException(e); } catch (MessagingException e) { throw new RuntimeException(e); } } } |
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 stpes, first to compile program and second to run it.
# javac SendMailJavaAPI.java # java SendMailJavaAPI
2 Comments
It is working fine in Windows 7 but not working in Windows 8
Veeramani mine is not working in window 7. guide me what to do