eclipsemavenspring-mvcmail-sender

java.lang.NoClassDefFoundError: Could not initialize class org.springframework.mail.javamail.SmartMimeMessage


I'm getting below error while sending email from a java web project.
IDE: eclipse
Java version: openjdk version "1.8.0_212-3-redhat"
Spring version: 5.1.6.RELEASE

java.lang.NoClassDefFoundError: Could not initialize class org.springframework.mail.javamail.SmartMimeMessage
at org.springframework.mail.javamail.JavaMailSenderImpl.createMimeMessage(JavaMailSenderImpl.java:340)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:373)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:365)

Following is the filtered dependency tree for mail
enter image description here


I have tried the following:-

NOTE: This was a working code but suddenly I'm getting this error now.
No Compilation error in project and war is also able to successfully deployed on the server.


Solution

  • There are package and class names collision among the following jars:-

    Problem cause:
    Both jars will be part of the build and all classes will be added to the classpath.
    Now the classes at the mercy of class load order and causing different version than expected.

    What triggers the problem:
    I have run the maven with force update of Snapshots/Releases
    Now the latest version 4.10.0 of the following dependency has jakarta.mail-api.jar as an internal dependency.

    <dependency>
        <groupId>com.google.api-ads</groupId>
        <artifactId>ads-lib</artifactId>
        <version>RELEASE</version>
    </dependency> 
    

    Solution: Use only one jar. In may case javax.mai-api.jar
    What to change: I have added the exclusion for the jakarta.mail-api.jar in pom.xml

    <dependency>
        <groupId>com.google.api-ads</groupId>
        <artifactId>ads-lib</artifactId>
        <version>RELEASE</version>
        <exclusions>
            <exclusion>
                <groupId>jakarta.mail</groupId>
                <artifactId>jakarta.mail-api</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    

    Key learning point : Use of Release/Snapshot version in pom.xml can lead to dependency conflicts and issues like NoClassDefFoundError if you run the maven with option force update of Snapshots/Releases