5

I am trying to send a register confirmation email in my spring MVC web application and Tomcat 7 using JavaMailSender but it always returns a NullPointerException. Can anyone help me find out why I get the null pointer? Below are my config settings:

web.xml

<!-- jndi mail session -->
<resource-ref>
    <description>
        Resource reference to a factory for javax.mail.Session
        instances that may be used for sending electronic mail
        messages, preconfigured to connect to the appropriate
        SMTP server.
    </description>
    <res-ref-name>mail/Session</res-ref-name>
    <res-type>javax.mail.Session</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

application-servlet.xml

    <!-- Mail Sender bean definition -->

<bean id="smtpSession" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName" value="java:comp/env/mail/session"/>
</bean>

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="session" ref="smtpSession"/>
     <!--
    <property name="host" value="smtp.gmail.com" />
    <property name="port" value="465" />
    <property name="username" value="abc@gmail.com" />
    <property name="password" value="test123" />
    <property name="protocol" value="smtp" />


    <property name="defaultEncoding" value="UTF-8"/> 

    <property name="javaMailProperties">
        <props>
            <prop key="mail.smtp.auth">true</prop>
            <prop key="mail.smtp.connectiontimeout">5000</prop>
            <prop key="mail.smtp.sendpartial">true</prop>
            <prop key="mail.smtp.userset">true</prop>
            <prop key="mail.mime.charset">UTF-8</prop>
            <prop key="mail.smtp.isSecure">true</prop>
            <prop key="mail.smtp.requiresAuthentication">true</prop>
            <prop key="mail.smtp.auth">true</prop>
            <prop key="mail.smtp.port">465</prop>
            <prop  key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
            <prop key="mail.smtp.socketFactory.fallback">false</prop>
            <prop key="mail.smtp.starttls.enable">true</prop>
            <prop key="mail.debug">true</prop>
        </props>
    </property>
     -->
</bean>

<bean id="simpleMailMessage" class="org.springframework.mail.SimpleMailMessage">
    <property name="from" value="abc@hotmail.com"/>       
</bean>

context.xml (in tomcat conf folder)

<Context path="/MVC" docBase="MVC" debug="5" crossContext="false">
<Resource name="mail/session" 
    auth="Container"
        type="javax.mail.Session"
        username="abc@gmail.com"
        password="test23"
        mail.debug="true"
        mail.user="abc@gmail.com"
        mail.password="test123"
        mail.transport.protocol="smtp"
        mail.smtp.host="smtp.gmail.com"
        mail.smtp.auth="true"
        mail.smtp.port="25"
        mail.smtp.starttls.enable="true"
/>

SendMail.java

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.MailParseException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Service;

import com.wbkit.mvc.domain.User;


@Service
public class SendMail 
{
@Autowired
private JavaMailSender mailSender;
@Autowired
private SimpleMailMessage simpleMailMessage;



public void confirmRegistrationMail(User user)
{


    MimeMessage message = mailSender.createMimeMessage();

    try
    {
        MimeMessageHelper helper = new MimeMessageHelper(message, true);

        helper.setFrom(simpleMailMessage.getFrom());
        helper.setTo(user.getEmail());
        helper.setSubject("MVC Registration");
        helper.setText("Hello " + user.getFirstName() + " "
              + user.getLastName() + ", \n" +
              " Your MVC Account Registration was successful. Your user ID is "
              + user.getEmail() + " and your password is "
              + user.getUserPass() + ".\n" +
              "You can now access the mobile applicatoin or the web application " 
              + " your user name (email) and password.");


    }
    catch (MessagingException e) 
    {
        throw new MailParseException(e);
    }
    mailSender.send(message);


}

public void requireApprovalMail(final User user)
{


}


}

Stack Trace:

4-Sep-2012 7:47:16 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [MVC] in context with path [/MVC] threw         exception [Request processing failed; nested exception is java.lang.NullPointerException]  with root cause
java.lang.NullPointerException
at com.wbkit.mvc.util.SendMail.confirmRegistrationMail(SendMail.java:79)
at com.wbkit.mvc.web.main.RegisterController.save(RegisterController.java:276)
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.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1812)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

java.lang.NullPointerException at com.wbkit.mvc.util.SendMail.confirmRegistrationMail(SendMail.java:79) points to

MimeMessage message = mailSender.createMimeMessage();

in SendMail.java. I removed some of the commented code I had.

Thanks for your suggestions and help.

kenju
  • 5,866
  • 1
  • 41
  • 41

5 Answers5

1

I've had the same error. It came from a manual instantiation of the class that had the JavaMailSender bean as an autowired field. In the code posted by the OP, that would be the SendMail service class.

This question shed some light on the phenomenon: the autowired fields of the manually created object did not receive any actual reference to the JavaMailSender bean because Spring can't know it is supposed to do its magic then. It's very obvious afterwards.

Hope this helps someone.

Community
  • 1
  • 1
AbVog
  • 1,435
  • 22
  • 35
0

It seems that you've included everything except the details of your exception.

Also, it looks like you're just making up property names. A bunch of the properties in your configuration are not valid JavaMail properties. Also, see this list of common mistakes.

Bill Shannon
  • 29,579
  • 6
  • 38
  • 40
0

Check your logging when the application starts up and see if you can see the JavaMailSender being wired into SendMail. You may have to set the org.springframework logging to DEBUG.

It seems to me that your wiring must be wrong, though I can't see why yet.

Rich Cowin
  • 668
  • 1
  • 8
  • 17
0

Remove the @Autowired from SimpleMailMessage and create the object of it inside confirmRegistrationMail() method:

public void confirmRegistrationMail(User user) {
    SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
}

This is probably because it's recommended to use the @Autowire for interface. e.g. JavaMailSender

Matt Ke
  • 3,599
  • 12
  • 30
  • 49
-1

Write @Service annotation on your helper class in which you have done the autowiring. And then use the @autowire annotation in the class where you are using that class.

Khawar
  • 1