Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.ClassCastException: javax.mail.Session cannot be cast to javax.mail.Session

Tags:

java

tomcat

I have been receiving this error when trying to run the following code to get a javax.mail.Session object using a tomcat context file.

        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        Session session = (javax.mail.Session) envCtx.lookup("mail/session");

This is the resource declaration in the context.xml.

  <Resource name="mail/Session" auth="Container"
        type="javax.mail.Session"
        mail.smtp.host="host"
        mail.smtp.user="user"
        mail.smtp.password="password"
        mail.smtp.auth="false"/>

I understand this can be due to me having the same library for the javax.mail.Session in my application server library(tomcat) folder and in my applications library folder, i have eliminated as many duplicate library files from my application library folder (e.g. mail.jar) that i can see have the javax.mail.Session as part of the library, now i am at a point where i am a still getting this error and not sure what other libraries could be the source of this problem, or is it some other issue that i am not aware of?

What would people suggest i do to find the source of this problem?

Thanks.

like image 686
JCS Avatar asked Aug 12 '13 11:08

JCS


4 Answers

This problem occurs in the server because the lib of Tomcat and you application both have their own copy of mail.jar (in WEB-INF/lib), so the classloaders can load two different Session.If you delete the mail.jarfrom your application, this problem will be solved.

like image 81
yuan Avatar answered Oct 21 '22 21:10

yuan


You're probably no longer having this issue, but for the next person to come here:

If you're using maven, add <scope>provided</scope> to your javax.mail dependency in pom.xml.

For instance, in my case:

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>YOUR_VERSION</version>
    <scope>provided</scope> <!-- This line is new -->
</dependency>

This solved the problem for me.

like image 32
Maura Avatar answered Oct 21 '22 21:10

Maura


use provided scope in maven javax.mail mail 1.4 provided

like image 2
darkZone Avatar answered Oct 21 '22 22:10

darkZone


If you already have the mail.jar in the lib of your server, delete the it from your application / pom file , this problem will be solved.

like image 1
Thakhani Tharage Avatar answered Oct 21 '22 22:10

Thakhani Tharage