0

I am new to JAVA EE, and I am working by myself on a project. Now, I want to deploy sending email function on a button click. In detail, I want my customer to submit their information and when they click on submit button, an email of receipt should be sent to their email. I will show my coding below.

First of all, here are my source files that are related to what I am doing.

EmailUtility.java

package com.jason;

import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
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 EmailUtility {
    public static void sendEmail(String host, String port,
            final String userName, final String password, String toAddress,
            String subject, String message) throws AddressException,
            MessagingException {

        // sets SMTP server properties
        Properties properties = new Properties();
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", port);
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");

        // creates a new session with an authenticator
        Authenticator auth = new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, password);
            }
        };

        Session session = Session.getInstance(properties, auth);

        // creates a new e-mail message
        Message msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(userName));
        InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
        msg.setRecipients(Message.RecipientType.TO, toAddresses);
        msg.setSubject(subject);
        msg.setSentDate(new Date());
        msg.setText(message);

        // sends the e-mail
        Transport.send(msg);

    }
}

And here is my PaymentServlet.java

package com.jason;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.jason.storeServlet.Command;

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;
import javax.mail.Authenticator;

/**
 * Servlet implementation class paymentServlet
 */
@WebServlet("/paymentServlet")
public class paymentServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */

    int quantity;
    String color;
    double size;
    double price;
    String productId;
    double totalPrice;
    double tax;
    DecimalFormat decimalFormat = new DecimalFormat("#.##");
    public enum Command {Buy,Submit,Confirm}
    private String host;
    private String port;
    private String user;
    private String pass;

    public void init() {

        ServletContext context = getServletContext();
        host = context.getInitParameter("host");
        port = context.getInitParameter("port");
        user = context.getInitParameter("user");
        pass = context.getInitParameter("pass");
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        HttpSession session = request.getSession();
        String action = request.getParameter("action");
        Command command = Command.valueOf(action);
        System.out.println(action);
        System.out.println("get");
        switch(command) {
            case Buy:
                this.buynow(request, response);
                break;

            case Submit:
                this.submit(request, response);
                break;

            case Confirm:
                this.confirm(request, response);
                break;

            default:
                break;
        }
    }


    private void confirm(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{
        HttpSession session = request.getSession();
        response.sendRedirect(request.getContextPath() + "/receipt.jsp");
        session.setAttribute("date", date());   
        Email(request, response);
    }

    private String date(){

        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy");
        return sdf.format(new Date());
    }

    protected void Email(HttpServletRequest request, HttpServletResponse response){
        String recipient = "some email";
        String subject = "Receipt for your order";
        String content = "We thank you for your purchase.";

        String resultMessage = "";

        try {
            EmailUtility.sendEmail(host, port, user, pass, recipient, subject,
                    content);
            resultMessage = "The e-mail was sent successfully";
        } catch (Exception ex) {
            ex.printStackTrace();
            resultMessage = "There were an error: " + ex.getMessage();
        }
    }

}

And here is web.xml file

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

 <context-param>
        <param-name>host</param-name>
        <param-value>smtp.gmail.com</param-value>
    </context-param>

    <context-param>
        <param-name>port</param-name>
        <param-value>587</param-value>
    </context-param>

    <context-param>
        <param-name>user</param-name>
        <param-value>some email</param-value>
    </context-param>

    <context-param>
        <param-name>pass</param-name>
        <param-value>some password</param-value>
    </context-param>
</web-app>

So the way it should work is that when a customer clicks on Confirm button it should deploy the confirm method which calls email method.

Here is the error I am getting:

org.apache.catalina.core.StandardWrapperValve invoke SEVERE: Servlet.service() for servlet [com.jason.paymentServlet] in context with path [/Practice4_Shopping] threw exception [Servlet execution threw an exception] with root cause java.lang.ClassNotFoundException: javax.mail.Authenticator at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1269) at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1104) at com.jason.paymentServlet.Email(paymentServlet.java:256) at com.jason.paymentServlet.confirm(paymentServlet.java:239) at com.jason.paymentServlet.doGet(paymentServlet.java:84) at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:475) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:651) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:498) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:796) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1374) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Unknown Source)

Grimthorr
  • 6,856
  • 5
  • 41
  • 53
  • Can you add two jars into WEB-INF/lib directory or webapp (or lib directory of the server): mail.jar activation.jar. this link might be helpful https://stackoverflow.com/questions/1630002/java-lang-noclassdeffounderror-javax-mail-authenticator-whats-wrong – user3509208 Nov 22 '17 at 17:25
  • Yes you were right. I thought that they go into referenced libraries. – Jason Yang Nov 24 '17 at 19:18

0 Answers0