I am creating a registration form using spring mvc in which email is one of the fields, once user is filled the details and click on register button , I would like to send an email to the given user email address with a random otp.

application context as well as dispatcher xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="  
        http://www.springframework.org/schema/beans  
        http://www.springframework.org/schema/beans/spring-beans.xsd  
        http://www.springframework.org/schema/context  
        http://www.springframework.org/schema/context/spring-context.xsd  
        http://www.springframework.org/schema/mvc  
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    <context:annotation-config />

    <tx:annotation-driven />

    <!-- Provide support for component scanning -->
    <context:component-scan base-package="com.uday" />

    <!--Provide support for conversion, formatting and validation -->
    <mvc:annotation-driven />



    <!-- Define Spring MVC view resolver -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/page/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>


    <bean id="dataSource"
        class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName"
            value="oracle.jdbc.driver.OracleDriver"></property>
        <property name="url"
            value="jdbc:oracle:thin:@localhost:1521:xe"></property>
        <property name="username" value="hr"></property>
        <property name="password" value="umashetti123"></property>
    </bean>

    <bean id="mysessionFactory"
        class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>

        <property name="mappingResources">
            <list>
                <value>Login_Detailshbm.xml</value>
            </list>
        </property>

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="checkWriteOperation">false</prop>

            </props>
        </property>
    </bean>

    <bean id="transactionManager"
        class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="mysessionFactory" />
    </bean>



    <bean id="d" class="com.uday.Login_DetailsDao">
        <constructor-arg ref="mysessionFactory" />
    </bean>

      <!-- SET default mail properties -->
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="smtp.gmail.com"/>
        <property name="port" value="587"/>
        <property name="username" value="[email protected]"/>
        <property name="password" value="password"/>
        <property name="javaMailProperties">
            <props>
                <prop key="mail.transport.protocol">smtp</prop>
                <prop key="mail.smtp.auth">true</prop>
                <prop key="mail.smtp.starttls.enable">true</prop>
                <prop key="mail.debug">true</prop>
            </props>
        </property>
    </bean>

    <bean
        class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="java.lang.Exception">Error</prop>
            </props>
        </property>
    </bean>

    <mvc:view-controller path="/WEB-INF/page/"
        view-name="login.jsp" />
    <mvc:resources mapping="/resources/**"
        location="/resources/" cache-period="31556926" />


</beans>    

Controller class

package com.uday;



import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;





@Controller
public class ControllerSignUp_Login {

    private final Login_DetailsDao dao;
    private Login_Details ld = new Login_Details();
    private String OtpMailed = "";
    private JavaMailSender mailSender;


    public ControllerSignUp_Login(Login_DetailsDao login_DetailsDao,JavaMailSender mailSender) {
        this.dao = login_DetailsDao;
        this.mailSender = mailSender;
    }

    @RequestMapping("/hello")
    @Transactional
    public String diaplay(@RequestParam("name") String name, @RequestParam("pass") String pass,Model m) {
        if(dao.isLogoinSuccessfull(name , pass)) {
            m.addAttribute("message", "Hello "+name+" You are successfully logged in");
            return "Success";
        }
        else {
            m.addAttribute("message", "Cannot validate given details.Please try again");
            return "login";
        }
    }

    @RequestMapping("/SignUp")
    public String redirect() {
        System.out.println("ControllerSignUp_Login.display()");
        return "signup";
    }

    @RequestMapping("/login")
    public String display() {
        System.out.println("ControllerSignUp_Login.display()");
        return "login";
    }

    @RequestMapping("/updateDetails")
    @Transactional
    public String display(HttpServletRequest req , Model M) {
        String firstName=req.getParameter("firstName");  
        String lastName=req.getParameter("lastName"); 
        String mobileNo=req.getParameter("mobileNo");  
        String address=req.getParameter("address");  
        String email=req.getParameter("email");  
        String password=req.getParameter("password");       
        if(checkLength(firstName)  && checkLength(lastName) && checkLength(mobileNo) && checkLength(address) && checkLength(email) &&  checkLength(password)) {

            ld.setFirstName(firstName);
            ld.setLastName(lastName);
            ld.setEmail(email);
            ld.setAddress(address);
            ld.setMobileNo(mobileNo);
            ld.setPassword(password);
//          dao.saveEmployee(ld);
//          M.addAttribute("message", "SignUp Successfull !! Thank You");
//          M.addAttribute("displayLogin", true);
            doSendEmail(email);     
            return "ValidationPage";
        }
        else {
            M.addAttribute("message","SignUp Failed !! All details are mandatory.");
            return "signup";


        }
    }

    @RequestMapping("/Home")
    public String displayy() {
        return "Home";
    }

    @RequestMapping("/")
    public String display1() {
        return "login";
    }

    public boolean checkLength(String s) {
        if(s != null && s.length() > 0) {
            return true;
        }
        return false;

    }

    @Transactional
    @RequestMapping("/submitToDB")
    public String submitToDataBase(HttpServletRequest req , Model M) {
        String otp = req.getParameter("otp");
        if(OtpMailed.equals(otp)) {
            dao.saveEmployee(ld);
            M.addAttribute("message", "SignUp Successfull !! Thank You");
            M.addAttribute("displayLogin", true);
            return "Success";
        }
        else {
            M.addAttribute("message","OTP Authorization failed");
            return "signup";
        }

    }


    @RequestMapping("/validate")
    public String  validateOtp() {
        return "Success";   
    }

    public String generateOtp() {
        String otp = "";
        for(int i = 0 ; i < 4 ; i++) {
            Double d = Math.ceil(Math.random()*10);
            int value = d.intValue();
            if(value  == 10) {
                otp = otp+1;
            }
            else {
                otp = otp+value;
            }
        }
        return otp;

    }
    public void doSendEmail(String mail) {
         String recipientAddress = mail;
         String subject = "One Time Verification <Uday>";
         String otpGenerated = generateOtp();
         this.OtpMailed = otpGenerated;
         String message = "Please use this OTP "+otpGenerated+ "to signup. ";

         SimpleMailMessage email = new SimpleMailMessage();
         email.setTo(recipientAddress);
         email.setSubject(subject);
         email.setText(message);
         mailSender.send(email);

    }

}


getting below exception on executing mailsender.send(email) method

logs


DEBUG: JavaMail version 1.4ea
DEBUG: java.io.FileNotFoundException: C:\Program Files\Java\jre1.8.0_201\lib\javamail.providers (The system cannot find the file specified)
DEBUG: !anyLoaded
DEBUG: not loading resource: /META-INF/javamail.providers
DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
DEBUG: Tables of loaded providers
DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc]}
DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]}
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: !anyLoaded
DEBUG: not loading resource: /META-INF/javamail.address.map
DEBUG: java.io.FileNotFoundException: C:\Program Files\Java\jre1.8.0_201\lib\javamail.address.map (The system cannot find the file specified)
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 587, isSSL false
220 smtp.gmail.com ESMTP p78sm5939377pfa.97 - gsmtp
DEBUG SMTP: connected to host "smtp.gmail.com", port: 587

EHLO TASL-umashetti
250-smtp.gmail.com at your service, [183.82.100.83]
250-SIZE 35882577
250-8BITMIME
250-ENHANCEDSTATUSCODES
250-PIPELINING
250 SMTPUTF8
DEBUG SMTP: Found extension "SIZE", arg "35882577"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "SMTPUTF8", arg ""
DEBUG SMTP: use8bit false
MAIL FROM:<[email protected]>
530 5.7.0 Must issue a STARTTLS command first. p78sm5939377pfa.97 - gsmtp
com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. p78sm5939377pfa.97 - gsmtp

    at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1388)
    at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:959)
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:583)
    at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:464)
    at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:322)
    at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:311)
    at com.uday.ControllerSignUp_Login.doSendEmail(ControllerSignUp_Login.java:160)
    at com.uday.ControllerSignUp_Login.display(ControllerSignUp_Login.java:82)
    at com.uday.ControllerSignUp_Login$$FastClassBySpringCGLIB$$d455b738.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:749)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
    at com.uday.ControllerSignUp_Login$$EnhancerBySpringCGLIB$$de92940a.display(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
    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:200)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:836)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1747)
    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)
QUIT
221 2.0.0 closing connection p78sm5939377pfa.97 - gsmtp

I have tried changing the port to 25 and 465 but no use

enter image description here

0 Answers