Tomcat 6 Javax.mail session envCtx.lookup(“mail/Se

2019-08-12 08:51发布

问题:

I am using Tomcat 6 to send a email client with Javax.mail APIs , i set up my configurations in server.xml as below

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

And in my web.xml as below

<resource-ref>
    <description>Resource reference to a container-managed JNDI JavaMail factory for sending e-mails.</description>
    <res-ref-name>mail/Session</res-ref-name>
    <res-type>javax.mail.Session</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

But when i tried to create a mail Session ...using context.lookup

ontext initCtx = new InitialContext();
            Context envCtx = (Context) initCtx.lookup("java:comp/env");
            *mailSession = (Session)envCtx.lookup("mail/Session");*

The call nvCtx.lookup("mail/Session"); is not returning....it goes and break in org/springframework/jms/listener/DefaultMessageListenerContainer ...

Any Clues .... I appreciate any help.

Thanks Vijay

回答1:

As you don't use spring use this:

Source: Apache Tomcat 6.0 Documentation - JDNI Resources

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

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(request.getParameter("from")));
InternetAddress to[] = new InternetAddress[1];
to[0] = new InternetAddress(request.getParameter("to"));
message.setRecipients(Message.RecipientType.TO, to);
message.setSubject(request.getParameter("subject"));
message.setContent(request.getParameter("content"), "text/plain");
Transport.send(message);


回答2:

Your configuration looks ok, may you need to clean the server first (if you use eclipse).

Anyway: If you use spring then you can use the spring Framwork to access the JNDI ressource:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/jee
    http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">

    <jee:jndi-lookup id="jndiEmailSession"
         jndi-name="java:comp/env/email/Session" />
</beans>