Tuesday, November 10, 2015

Sending a mail in Java


Got this Error..???

"javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:"

Are you searching for the code to send a Email from java program? OR Are you stuck while sending a mail due to this exception.!!! Dont worry I will help you getting it solved.

Step 1: Disable your antivirus or firewalls until we finish this.


Here is how to disable the Avast Shields.. Similarly search for yours.

Step 2: Importing SSL Certificate into your Computer.

  • Open your Gmail and click on the lock symbol.


  • Now Go to connection and open certificate information.
  • Now Go to Details and Then Copy to file.

  • Then just do next next next then browse for file location, give a name and save.
ok... Now we are done saving the certificate, now we need to install it. copy that certificate into C:\Program Files\Java\jdk1.8.0_25\jre\lib\security this location. if you have installed windows in c drive. After pasting, double click that and run it.


now click on Install Certificate and then just next next and finish. then you are done.

Step 3: Getting jar file from apache.

Click here to download the zip file for the jar files which are going to use in our program.

Just extract and add the commons-email-1.4.jar file to your project folder in netbeans.

Step 4: Writing the program.

  1. import java.util.logging.Level;
  2. import java.util.logging.Logger;
  3. import org.apache.commons.mail.*;
  4. /**
  5.  *
  6.  * @author Bisudw
  7.  */
  8. public class Sender {
  9.     public static void main(String [] args){
  10.         try {
  11.             Email email = new SimpleEmail();
  12.             email.setHostName("smtp.gmail.com");
  13.             email.setSmtpPort(465);
  14.             email.setSSLCheckServerIdentity(true);
  15.             email.setStartTLSRequired(true);
  16.             email.setAuthenticator(new DefaultAuthenticator("yourmail@gmail.com", "password"));
  17.             email.setSSLOnConnect(true);
  18.             email.setFrom("yourmail@gmail.com");
  19.             email.setSubject("Test Mail");
  20.             email.setMsg("This is a test mail.");
  21.             email.addTo("receiver's mail@gmail.com");
  22.             email.send();
  23.             System.out.println("Message Sent Successfully..!!");
  24.         } catch (EmailException ex) {
  25.             //System.out.println("Message Sending Filed...!!!");
  26.             Logger.getLogger(Sender.class.getName()).log(Level.SEVERE, null, ex);
  27.         }
  28.     }
  29. }

just run it... If you get any further errors.. Please comment below.

Thank You.

No comments:

Post a Comment