users@glassfish.java.net

Re: Glassfishv2u1-JavaMail Session and Gmail problem

From: <glassfish_at_javadesktop.org>
Date: Tue, 01 Jul 2008 15:43:45 PDT

I do not know if you can get this to work without patching Continuum.

GlassFish does not support loading passwords from mail resource properties, nor does JavaMail. (Tomcat supports this by loading the password from the resource and configuring an authentication object for the mail session - GlassFish does not - I filed an RFE for this: https://glassfish.dev.java.net/issues/show_bug.cgi?id=5247)

If an application running on GlassFish needs to send email via an authenticating SMTP server such as GMail, the application (Servlet in this case I suppose) needs to acquire the password itself and use the connect method directly, e.g. something like this:

[code]
        Context c = new InitialContext();
        Session mailSession = (Session) c.lookup("java:comp/env/mail/Session");

        // if you want to read username/password from resource in your own code, you can get properties like this:
        Properties props = mailSession.getProperties();
        String username = (String) props.get("mail.smtp.user");
        String password = (String) props.get("mail.smtp.password");
        // or you can retrieve username/password from session credentials, or ???

        // create message
        MimeMessage message = new MimeMessage(mailSession);
        message.setSubject(subject_text);
        message.setRecipients(javax.mail.Message.RecipientType.TO, javax.mail.internet.InternetAddress.parse(recipient_email, false));
        message.setText(body_text);
        message.saveChanges();

        // send message
        Transport transport = mailSession.getTransport("smtp");
        try {
            transport.connect(username, password);
            transport.sendMessage(message, message.getAllRecipients());
        } finally {
            transport.close();
        }
[/code]
[Message sent by forum member 'peterwx' (peterwx)]

http://forums.java.net/jive/thread.jspa?messageID=283814