Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaMailSender returning null pointer exception

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="[email protected]" />
    <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="[email protected]"/>       
</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="[email protected]"
        password="test23"
        mail.debug="true"
        mail.user="[email protected]"
        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.

like image 712
Freddie Frederick Avatar asked Nov 24 '22 17:11

Freddie Frederick


1 Answers

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.

like image 164
AbVog Avatar answered Nov 27 '22 07:11

AbVog