使用Spring Mail发送电子邮件时获取空指针异常

时间:2018-10-07 01:51:03

标签: java spring javamail

我正在尝试使用spring做电子邮件功能(出于我的学习目的)。 以下是代码段:

@Autowired
static
ApplicationContext applicationContext;
/**
 * <p>
 * Utility classes, which are collections of static members, are not meant to be
 * instantiated. Even abstract utility classes, which can be extended, should
 * not have public constructors.
 * 
 * Java adds an implicit public constructor to every class which does not define
 * at least one explicitly. Hence, at least one non-public constructor should be
 * defined.
 * 
 * </p>
 */
private EmailUtility() {
}

//@Autowired
//private static JavaMailSender mailSender;

public static void sendSimpleMessage(String to, String subject, String text, boolean trainTicket,
        boolean flightTicket) throws MessagingException {



    JavaMailSender mailSender = applicationContext.getBean("mailSender",JavaMailSenderImpl.class);
    MimeMessage message = mailSender.createMimeMessage();
    String pathToAttachment = "";
    MimeMessageHelper helper = new MimeMessageHelper(message, true);

    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(text);

    if (trainTicket && !flightTicket) {
        pathToAttachment = AppConstants.TRAIN_TICKET_FILE;
    } else if (!trainTicket && flightTicket) {
        pathToAttachment = AppConstants.FLIGHT_TICKET_FILE;
    }

    if (Objects.nonNull(pathToAttachment) && !pathToAttachment.isEmpty()) {
        FileSystemResource file = new FileSystemResource(new File(pathToAttachment));
        helper.addAttachment("Ticket", file);
    }

    mailSender.send(message);
}

}

我的应用程序上下文:

<!-- Step 3: Add support for component scanning -->
<context:component-scan base-package="com.patcyy.vamonos" />

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

 <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="abcd.abcd.com"/>
    <property name="port" value="2525"/>
    <property name="username" value="admin@abcd.com"/>
    <property name="password" value="test"/>
    <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>

在初始化JavaMailSender时,我得到了nullpointer异常。(在这一行中,JavaMailSender mailSender = applicationContext.getBean(“ mailSender”,JavaMailSenderImpl.class);)

StackTrace:

java.lang.NullPointerException     在com.patcyy.vamonos.utills.EmailUtility.sendSimpleMessage(EmailUtility.java:61)     在com.patcyy.vamonos.services.StaticContentService.postEnquiry(StaticContentService.java:82)     在com.patcyy.vamonos.controller.StaticContentController.postEnquiry(StaticContentController.java:143)     在sun.reflect.NativeMethodAccessorImpl.invoke0(本机方法)处     在sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)     在sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)     在java.lang.reflect.Method.invoke(Method.java:498)     在org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)     在org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)     在org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)     在org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:891)     在org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797)     在org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)     在org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)     在org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)     在org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974)     在org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:877)     在javax.servlet.http.HttpServlet.service(HttpServlet.java:660)     在org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851)     在javax.servlet.http.HttpServlet.service(HttpServlet.java:741)     在org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)     在org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)     在org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)     在org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)     在org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)     在org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)     在org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)     在org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)     在org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)     在org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)     在org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668)     在org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)     在org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)     在org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)     在org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)     在org.apache.coyote.AbstractProtocol $ ConnectionHandler.process(AbstractProtocol.java:770)     在org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.doRun(NioEndpoint.java:1415)     在org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)     在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)     在java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:624)     在org.apache.tomcat.util.threads.TaskThread $ WrappingRunnable.run(TaskThread.java:61)     在java.lang.Thread.run(Thread.java:748)

1 个答案:

答案 0 :(得分:0)

我认为主要的问题是您将实用程序定义为服务。 无论如何,如果您想在非托管对象中使用Spring托管bean,可以执行以下操作

@Component public class ContextInitializer {

@Autowired
private JavaMailSender mailSender;

@PostConstruct
public void postConstruct() {
    EmailUtility.setMailSender(mailSender);
}

}

并在EmailUtility类中添加一个setter方法。