JavaMail + MailConfiguration cannot be cast to javax.mail.Session

20 Nov
2009

If you’re trying out JavaMail with JavaEE (6) on Glassfish and get a ClassCastException like these

SEVERE: java.lang.ClassCastException: com.sun.enterprise.deployment.MailConfiguration cannot be cast to javax.mail.Session
javax.faces.el.EvaluationException: java.lang.ClassCastException: com.sun.enterprise.deployment.MailConfiguration cannot be cast to javax.mail.Session
        at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
        at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
        at javax.faces.component.UICommand.broadcast(UICommand.java:315)
        at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:774)
        at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1266)
        at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:82)
        at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
        at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
        at javax.faces.webapp.FacesServlet.service(FacesServlet.java:310)
        at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1522)
...

when trying to inject the Mail-Session into your bean, try to do it the following way

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
@ManagedBean(name = "registrationController")
public class RegistrationController {
 
@EJB
RegistrationServiceImpl registrationService;
 
@Resource(type = Session.class, name = "mail/projectMailSession", mappedName = "mail/projectMail")
Session mailSession;
 
private Member member = new Member();
 
....
 
private void sendRegistrationEmail(String activationCode) {
try
{
Message msg = new MimeMessage(this.mailSession);
msg.setSubject("Project X: Activation needed! ");
msg.setSentDate(new Date());
msg.setFrom();
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(member.getEmailAddress(), false));
msg.setText("Welcome at Project X! \n" +
"Aktivierungscode: "+ activationCode + "\n\n bis bald!");
Transport.send(msg);
}
catch (MessagingException e)
{   e.printStackTrace();  }
}

The important part is bold printed: You have to

  1. inject the mail-session with the @Resource annotation,
  2. specify the class you want (type = Session.class),
  3. specify an alias for the jndi-name with this object ( here “mail/projectMailSession” )
  4. and specify the jndi name you used to specify the mail-session in the administration backend (I used “mail/projectMail”).

I’ve found the missing bits on this thread
http://old.nabble.com/Problem-on-configuring-Java-Mail-Session-td15955905.html

Comment Form

top