0

Recently I made web application which sends an E-mail. The code is working fine I have no error, I have runtime exception

(javax.net.ssl.SSLException: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty)

My Code For index.jsp is:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title> Java Mail </title>
</head>
<body>
    <form action="sendMail.jsp" method="POST">
        <table border="0" align="center" cellpadding="5">
            <tbody>
                <thead><tr> <td colspan="3" align="center">
                <b> Send Mail </b> </td> </tr> </thead>
                <tr>
                    <td> To </td> <td> : </td>
                    <td> <input type="text" name="to" value="" /> </td>
                </tr>
                <tr>
                    <td> Subject </td> <td> : </td>
                    <td> <input type="text" name="subject" value="" /> </td>
                </tr>
                <tr>
                    <td> Message </td> <td> : </td>
                    <td> <textarea name="message" rows="8" cols="30">
                    </textarea></td>
                </tr>
                <tr>
                    <td colspan="3" align="center">
                    <input type="submit" value="Send Mail" />

                    <input type="reset" value="Reset" />
                    <td>
                </tr>
            </tbody>
        </table>
    </form>
</body>
</html>

My code for sendMail.jsp is:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=">
    <jsp:useBean id="mail" scope="session" class="jMail.Mail" />
    <jsp:setProperty name="mail" property="to" param="to" />
    <jsp:setProperty name="mail" property="from" value="MyEmail@gmail.com" />
    <jsp:setProperty name="mail" property="smtpServ" value="smtp.gmail.com" />
    <jsp:setProperty name="mail" property="subject" param="subject" />
    <jsp:setProperty name="mail" property="message" param="message" />
</head>
<body>
    <%
        String to = mail.getTo();
        int result;
        result = mail.sendMail();
        if (result == 0) {
            out.println(" Mail Successfully Sent to " + to);
        } else {
            out.println(" Mail NOT Sent to " + to);
        }
    %>
</body>
</html>

My Code For Mail.java is:

package jMail;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class Mail {
private String to;
private String from;
private String message;
private String subject;
private String smtpServ;

/**
 * @return the to
 */
public String getTo() {
    return to;
}

/**
 * @param to the to to set
 */
public void setTo(String to) {
    this.to = to;
}

/**
 * @return the from
 */
public String getFrom() {
    return from;
}

/**
 * @param from the from to set
 */
public void setFrom(String from) {
    this.from = from;
}

/**
 * @return the message
 */
public String getMessage() {
    return message;
}

/**
 * @param message the message to set
 */
public void setMessage(String message) {
    this.message = message;
}

/**
 * @return the subject
 */
public String getSubject() {
    return subject;
}

/**
 * @param subject the subject to set
 */
public void setSubject(String subject) {
    this.subject = subject;
}

/**
 * @return the smtpServ
 */
public String getSmtpServ() {
    return smtpServ;
}

/**
 * @param smtpServ the smtpServ to set
 */
public void setSmtpServ(String smtpServ) {
    this.smtpServ = smtpServ;
}


public int sendMail(){
    try
    {
        Properties props = System.getProperties();
          // -- Attaching to default Session, or we could start a new one --
          props.put("mail.transport.protocol", "smtp" );
          props.put("mail.smtp.starttls.enable","true" );
          props.put("mail.smtp.host",smtpServ);
          props.put("mail.smtp.auth", "true" );
          Authenticator auth = new SMTPAuthenticator();
          Session session = Session.getInstance(props, auth);
          // -- Create a new message --
          Message msg = new MimeMessage(session);
          // -- Set the FROM and TO fields --
          msg.setFrom(new InternetAddress(from));
          msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to,     false));
          msg.setSubject(subject);
          msg.setText(message);
          // -- Set some other header information --
          msg.setHeader("MyMail", "Mr. XYZ" );
          msg.setSentDate(new Date());
          // -- Send the message --
          Transport.send(msg);
          System.out.println("Message sent to"+to+" OK." );
          return 0;
    }
    catch (Exception ex)
    {
      ex.printStackTrace();
      System.out.println("Exception "+ex);
      return -1;
    }
}



private class SMTPAuthenticator extends javax.mail.Authenticator {
    @Override
    public PasswordAuthentication getPasswordAuthentication() {
        String username =  "MyEmail@gmail.com";           
        String password = "MyPassword";
        return new PasswordAuthentication(username, password);
    }
  }

}

Please help me I always have runtime exception:

Exception javax.mail.MessagingException: Could not convert socket to TLS; nested exception is: javax.net.ssl.SSLException: java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty

Bastien Jansen
  • 8,756
  • 2
  • 35
  • 53
user2284478
  • 3
  • 1
  • 2
  • 5

2 Answers2

0

Put the following properties

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", "465");

Example using gmail SMTP over SSL

NullPointerException
  • 3,732
  • 5
  • 28
  • 62
0

Here is my code,

import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class SendMail {
     public static int Send(String SMTPServer,
                        String Sender,
                        String Recipient,
                        String Subject,
                        String Body,
                        String ErrorMessage,
                        String Attachments) {
    // Error status;
    int ErrorStatus = 0;

    // Create some properties and get the default Session;
    final String username = Sender;
    final String password = "pswd";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    Session session = Session.getInstance(props,
      new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
      });

    try {
       // Create a message.
       MimeMessage msg = new MimeMessage(session);

       // extracts the senders and adds them to the message.
       // Sender is a comma-separated list of e-mail addresses as per RFC822.
       {
          InternetAddress[] TheAddresses = InternetAddress.parse(Sender);
          msg.addFrom(TheAddresses);
       }

       // Extract the recipients and assign them to the message.
       // Recipient is a comma-separated list of e-mail addresses as per RFC822.
       {
          InternetAddress[] TheAddresses = InternetAddress.parse(Recipient);
          msg.addRecipients(Message.RecipientType.TO,TheAddresses);
       }

       // Subject field
       msg.setSubject(Subject);

       // Create the Multipart to be added the parts to
       Multipart mp = new MimeMultipart();

       // Create and fill the first message part
       {
          MimeBodyPart mbp = new MimeBodyPart();
          mbp.setText(Body);

          // Attach the part to the multipart;
          mp.addBodyPart(mbp);
       }

       // Attach the files to the message
       if (null != Attachments) {
          int StartIndex = 0, PosIndex = 0;
          while (-1 != (PosIndex = Attachments.indexOf("///",StartIndex))) {
             // Create and fill other message parts;
             MimeBodyPart mbp = new MimeBodyPart();
             FileDataSource fds =
             new FileDataSource(Attachments.substring(StartIndex,PosIndex));
             mbp.setDataHandler(new DataHandler(fds));
             mbp.setFileName(fds.getName());
             mp.addBodyPart(mbp);
             PosIndex += 3;
             StartIndex = PosIndex;
          }
          // Last, or only, attachment file;
          if (StartIndex < Attachments.length()) {
             MimeBodyPart mbp = new MimeBodyPart();
             FileDataSource fds = new FileDataSource(Attachments.substring(StartIndex));
             mbp.setDataHandler(new DataHandler(fds));
             mbp.setFileName(fds.getName());
             mp.addBodyPart(mbp);
          }
       }

       // Add the Multipart to the message
       msg.setContent(mp);

       // Set the Date: header
       msg.setSentDate(new Date());

       // Send the message;
       Transport.send(msg);
    } catch (MessagingException MsgException) {
        System.out.println("blows here");
        ErrorMessage = MsgException.toString();
        Exception TheException = null;
        if ((TheException = MsgException.getNextException()) != null)
         ErrorMessage += "\n" + TheException.toString();
         ErrorStatus = 1;
    }
    System.out.println(ErrorMessage);
    return ErrorStatus;
 } // End Send method

    public static void main(String args[]){
        SendMail.Send("smtp.gmail.com", "my_mail@gmail.com", "my_mail@gmail.com",
                 "try sending mail", "came? ","" ,null); 
    }


 } // End of public class SendMail

Sorry about indentation

Try now. hopefully, it will work

here is the output mail. in my computer it sends.

enter image description here

smttsp
  • 4,011
  • 3
  • 33
  • 62
  • @user2284478: you need to change code, but this sends mail at least – smttsp Apr 16 '13 at 15:51
  • can you upload your project please ? – user2284478 Apr 16 '13 at 15:54
  • There's no main method >. – user2284478 Apr 16 '13 at 15:55
  • is it not working? I just editted code. Write your mail address instead of my_mail@gmail.com and password that is inside the send method – smttsp Apr 16 '13 at 16:04
  • With your props Still Gives me the same exception, but i replaced your props by NullPointerException props, the out put is always empty and there's no build succeeded statment ! – user2284478 Apr 16 '13 at 16:13
  • did you only copy my props? if my code is working and your code is not working, you should better apply my code to your problem, which is not supposed to be that hard, declaring some variables outside of the method and deleting some parameters. doesnt look so hard to me, and I think you can do it, too. – smttsp Apr 16 '13 at 16:18
  • Look, I created new java class and named it like you SendMail then I copied all your code and changed the username and password for mine and I also replaced some parameters like subject,body and recipient then i copied the main method you added then I ran my program, the result is (there's no Error, No Exception , No Email Was Sent, No Output , No Statement Appeared in green which says build succeeded), Now Tell me What is wrong ?? – user2284478 Apr 16 '13 at 16:28
  • did you have a look at your mail whether it has send or not? – smttsp Apr 16 '13 at 16:39
  • I just tried it again, it doesnt give any error or print out, but it sends data. I m adding image to my answer – smttsp Apr 16 '13 at 16:48
  • I tried to use wrong password , nothing happened also !! I tried to use cmd telnet smtp.gmail.com 465 ,, nothing happened but when I try to use telnet smtp.gmail.com 587 ,, server replies, however, I tried to use the 587 port , I have the exception about the trustAnchors parameter must be non-empty – user2284478 Apr 16 '13 at 16:49
  • I tried to use wrong password , nothing happened also !! I tried to use cmd telnet smtp.gmail.com 465 ,, nothing happened but when I try to use telnet smtp.gmail.com 587 ,, server replies, however, I tried to use the 587 port , I have the exception about the trustAnchors parameter must be non-empty – user2284478 Apr 16 '13 at 17:04
  • I have no idea what is the reason for this error. you can use, system.out.print()'s to see what is going on, which methods are used, etc... I dont know more than that – smttsp Apr 16 '13 at 19:52