-1

I am trying to send an email but before I was getting a nullpointerexception error which was due to mailSender not getting set correctly, now I edited the code as it is shown below and I am not getting any exception but the code breaks at the line

MimeMessage message = mailSender.createMimeMessage();

Here is my code (both sendMail() and addNewAlarm() are inside the same class "ElementService"):

public class ElementService implements ApplicationContextAware {
    private ApplicationContext ac;



public void sendMail(String toAddress, String subject, String body) throws  Exception{

   JavaMailSender mailSender = (JavaMailSender) ac.getBean("mailSender");
   MimeMessage message = mailSender.createMimeMessage();

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

    helper.setFrom("xxx@gmail.com");
    helper.setTo(toAddress);
    helper.setSubject(subject);
    helper.setText(body);


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

  }    

   //I want an email to be sent every 30 seconds
   @Scheduled(fixedDelay = 30*1000)
   public void function2RepeatEvery30Seconds()
   {
       MailService mailer = (MailService) ac.getBean("mailService");
       mailer.sendMail("xxx@hotmail.com","subject","body");
       //does other stuff..

    }  
    @Override
    public void setApplicationContext(ApplicationContext ac) throws BeansException {
        this.ac = ac;
    }

}

These are the beans in my xml:

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">

<!-- SMTP settings -->
<property name="host" value="smtp.gmail.com" />
<property name="port" value="587" />
<property name="username" value="***@gmail.com" />
<property name="password" value="*****" />

<property name="javaMailProperties">
    <!-- additional properties specific to JavaMail -->
    <props>
        <prop key="mail.transport.protocol">smtp</prop>
        <prop key="mail.smtp.auth">true</prop>
        <prop key="mail.smtp.starttls.enable">true</prop>
    </props>
</property>
</bean>

In debug mode I can see that mailSender has been set according to the properties shown on the mailSender bean.

  • You should show the stacktrace. But it is at least *uncommon* to have a smtp server on port 110 ... – Serge Ballesta Oct 31 '14 at 13:58
  • I pasted the stacktrace, and I have tried ports: 587,25 as well. – iangelopoulos Oct 31 '14 at 15:10
  • If you use localhost as mailhost, **you** should know what smtp server is running and on what port. And the stacktrace says that the error occurs in `ElementService.addNewAlarm` ! Fix that first and come again when the error is in the class you show – Serge Ballesta Oct 31 '14 at 15:24
  • addNewAlarm is the function where sendMail() is called. I edited the code and it can be seen now – iangelopoulos Oct 31 '14 at 15:36
  • Could you say what line is `ElementService.java:1483` ? – Serge Ballesta Oct 31 '14 at 15:39
  • it's this line mailer.sendMail("xxx@hotmail.com","subject","body"); – iangelopoulos Oct 31 '14 at 15:46
  • and the smtp port is 25 – iangelopoulos Oct 31 '14 at 15:48
  • The error says : variable `mailer` is null at that place. As you get it directly from the application context, it looks like you never load the xml file. I now think you problem is how you bootstrap the application context ... – Serge Ballesta Oct 31 '14 at 15:52
  • Ok I edited the code so that I don't have to deal with wiring two different Services. Now my problem is that I get no exception at all. Obviously, I have some basic java ignorance on exceptions.. – iangelopoulos Nov 03 '14 at 11:03
  • What means *I am not getting any exception but the code breaks at the line * ? I really **cannot** understand that ! – Serge Ballesta Nov 03 '14 at 11:29
  • The debugger never reaches the breakpoints I have set on the lines containing "throw", or any other brakepoint after "MimeMessage message = mailSender.createMimeMessage();" (I have set brakepoints on every line) – iangelopoulos Nov 03 '14 at 11:59
  • And does `mailSender` looks ok in the debugger or is it null ? (before executing line `MimeMessage message = mailSender.createMimeMessage();`) – Serge Ballesta Nov 03 '14 at 13:06
  • Yes, it gets the values that are set as bean properties. – iangelopoulos Nov 03 '14 at 13:22
  • Please add logging (at least `System.out.println`) just before and just after the line. Something like : JavaMailSender mailSender = (JavaMailSender) ac.getBean("mailSender"); if (mailSender == null) { System.out.println("Before : mailSender is NULL"); } else { System.out.println("Before : " + mailSender.getClass.toString()); } MimeMessage message = mailSender.createMimeMessage(); Sytem.out.println(" After - message : " + (message == null) ? "NULL" : message.getClass().toString()); – Serge Ballesta Nov 03 '14 at 13:34
  • mailSender is not null and this is what it prints : `class org.springframework.mail.javamail.JavaMailSenderImpl` – iangelopoulos Nov 03 '14 at 14:38
  • And then this: `TaskUtils$LoggingErrorHandler:95 Unexpected error occurred in scheduled task. java.lang.NoClassDefFoundError: com/sun/mail/util/MessageRemovedIOException at org.springframework.mail.javamail.JavaMailSenderImpl.createMimeMessage(JavaMailSenderImpl.java:323) at gr.mobics.allweb.service.ElementService.sendMail2(ElementService.java:1570) at gr.mobics.allweb.service.ElementService.functions2RepeatEvery5Minutes(ElementService.java:2170)` and more... Line 1570 is this: `MimeMessage message = mailSender.createMimeMessage();` – iangelopoulos Nov 03 '14 at 14:41
  • And isn't that an Exception ? If you give incoherent elements it is not possible to help you. This error says *javamail is not in classpath*. It should be present in `javaee-web-api-6.0.jar` ... – Serge Ballesta Nov 03 '14 at 15:03
  • Yes, I was using only brakepoints. I thought every exception should be caught by try, catch(Exception e). Now I used log4j to see what was printed. And what I did was to change the dependency (in maven) from ` javax.mail javax.mail-api 1.5.2 ` to ` com.sun.mail javax.mail 1.5.2 ` – iangelopoulos Nov 03 '14 at 15:22
  • An Exception is caught in catch block only if it was thrown in the try block. – Serge Ballesta Nov 03 '14 at 15:50

2 Answers2

2

I finally did it!! Thanks to Serge Ballesta of course. I should have been using log4j all along... I researched the Exception MessageRemovedIOException and I found this post java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger for JUnit test case for Java mail where there is a suggestion in the comments to change

<dependency> <groupId>javax.mail</groupId> <artifactId>javax.mail-api</artifactId> <version>1.5.2</version> </dependency>

to

<dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.5.2</version> </dependency>

I also had to change this:

<prop key="mail.smtp.starttls.enable">true</prop>

to this:

<prop key="mail.smtp.starttls.enable">false</prop>

Thank you very much for your time and advice @Serge Ballesta!

Community
  • 1
  • 1
0

Ok, obviously the mailSender is null which causes the error. My guess would be that your @Autowired annotation is not processed. Do you have AutowiredAnnotationBeanPostProcessor registered? You can do that for example by using <context:annotation-config /> in your Spring configuration.

Other option (without using @Autowired) is to manually specify the dependency on mailSender in your mailService bean definition like so:

<bean id="mailService" class="gr.mobics.allweb.service.MailService" scope="singleton">
    <property name="mailSender" ref="mailSender" />
</bean>

I have not tested this, but it seems like this is the cause of your problem. If these solutions don't work you, leave a comment and I'll try to update the answer.

Bohuslav Burghardt
  • 33,626
  • 7
  • 114
  • 109
  • I had not registered AutowiredAnnotationBeanPostProcessor before. Now I placed above the beans and added http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd in schemaLocation not really knowing what I'm doing.. – iangelopoulos Oct 31 '14 at 15:12
  • Now I am getting this error: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter]: Constructor threw exception; nested exception is java.lang.OutOfMemoryError: PermGen space – iangelopoulos Oct 31 '14 at 15:15
  • That out of memory error does not seem like it is directly related to the original problem. Try increasing the permgen memory to see if that helps (http://www.mkyong.com/tomcat/tomcat-javalangoutofmemoryerror-permgen-space/) – Bohuslav Burghardt Oct 31 '14 at 17:47