如何将spring mail session jndi xml配置迁移到java config

时间:2014-09-19 04:06:26

标签: java spring-mvc jndi

我是Spring MVC的新手。我在Wildfly 8.0应用服务器上配置了一个邮件会话。我使用的是Spring 3.2。我正在使用这样的查找:

<jee:jndi-lookup id="myMailSession"
             jndi-name="java:jboss/mail/Email"
             expected-type="javax.mail.Session" />

但是,我非常想在Java Config中弄清楚如何做到这一点。 如何将这个基于xml的JNDI查找迁移到java配置?

2 个答案:

答案 0 :(得分:5)

最后,我使用java配置获得了JNDI Lookup。

@Bean
public JavaMailSenderImpl javaMailSenderImpl() {
    JavaMailSenderImpl mailSenderImpl = new JavaMailSenderImpl();
    mailSenderImpl.setSession(session());
    return mailSenderImpl;
}

public Session session(){
    JndiTemplate template = new JndiTemplate();
    Session session = null;
    try {
         session = (Session) template.lookup("java:jboss/mail/Email");
    } catch (NamingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return session;
}

上面的代码片段相当于JNDI Lookup邮件xml配置。

<jee:jndi-lookup id="myMailSession"
         jndi-name="java:jboss/mail/Email"
         expected-type="javax.mail.Session" /> 

答案 1 :(得分:1)

您可以使用春季邮件配置邮件发件人

<?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:int="http://www.springframework.org/schema/integration"
        xmlns:int-mail="http://www.springframework.org/schema/integration/mail"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
               http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
               http://www.springframework.org/schema/context
               http://www.springframework.org/schema/context/spring-context-3.2.xsd
               http://www.springframework.org/schema/integration
               http://www.springframework.org/schema/integration/spring-integration.xsd
               http://www.springframework.org/schema/util
               http://www.springframework.org/schema/util/spring-util-3.2.xsd
               http://www.springframework.org/schema/integration/mail
               http://www.springframework.org/schema/integration/mail/spring-integration-mail.xsd">

        <util:properties id="mailProperties"
            location="file:${mf_home}/conf/alertas/mail.properties" />

        <!-- Configuracion para velocity template para mensajes -->

        <bean id="velocityEngine"
            class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
            <property name="velocityProperties">
                <props>
                    <prop key="resource.loader">file</prop>
                    <prop key="file.resource.loader.class">
                        org.apache.velocity.runtime.resource.loader.FileResourceLoader
                    </prop>
                    <prop key="file.resource.loader.path">#{systemProperties['mf_home']}/conf/alertas/templates
                    </prop>
                    <prop key="file.resource.loader.cache">true</prop>
                </props>
            </property>
        </bean>

        <!-- Configuracion envio de correos -->
        <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">

            <property name="host" value="#{mailProperties['mail.smtp.host']}" />
            <property name="username" value="#{mailProperties['mail.smtp.user']}" />
            <property name="password" value="#{mailProperties['mail.smtp.password']}" />
            <property name="port" value="#{mailProperties['mail.smtp.port']}" />

            <property name="javaMailProperties">
                <props>
                    <prop key="mail.smtp.auth">#{mailProperties['mail.smtp.auth']}</prop>
                    <prop key="mail.smtp.starttls.enable">#{mailProperties['mail.smtp.starttls.enable']}</prop>
                </props>
            </property>
        </bean>

        <bean id="mailTransformerBean" class="com.praxis.desvucem.alarms.transformer.MailTransformer" />

    </beans>

您只需要将此配置上下文导入主应用程序上下文。

您还需要使用示例代码:

package com.praxis.desvucem.alarms.transformer;

import java.util.HashMap;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.inject.Inject;
import org.apache.velocity.app.VelocityEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.integration.Message;
import org.springframework.integration.MessageHeaders;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.velocity.VelocityEngineUtils;

import com.praxis.desvucem.alarms.mensajes.Mensaje;
import com.praxis.desvucem.alarms.domain.MfCContactoAlarma;

    public class MailTransformer {

        private static Logger log = LoggerFactory.getLogger(MailTransformer.class);

        private String templateSufijo = "Email.vm";

        /**
         * Inyecta propiedades a from.
         */
        public @Value("#{mailProperties['mail.smtp.from']}")
        String from;

        /**
         * Inyecta propiedades a sendToUser.
         */
        public @Value("#{mailProperties['mail.send.user.default']}")
        String sendToUser;

        @Inject
        private VelocityEngine velocityEngine;

        @Inject
        private JavaMailSender mailSender;

        /**
         * Convierte mensajes de tipo Mensaje a MimeMessage y este pueda ser enviado
         * por el adaptador de mail.
         * @param msj {@link Mensaje} Mensaje Recive el mensaje
         * @return MimeMessage {@link MimeMessage} Regresa el mensaje convertido en
         * MimeMessage
         * @throws Exception al generar MimeMessage en MailTransformer
         */
        public MimeMessage mensajeToMimeMessage(Message<?> mensaje) {
            MfCContactoAlarma contactoAlarma = (MfCContactoAlarma) mensaje.getPayload();
            MessageHeaders header = mensaje.getHeaders();
            String mensajeReal = header.get("mensaje").toString();

            Map<String, Object> model = new HashMap<String, Object>();

            model.put("texto", mensajeReal);

            MimeMessage mimeMessage = null;

            String destinatarios = contactoAlarma.getConNombre();

            if (destinatarios == null) {

                log.info("Enviando mensaje  por correo al destinatario por defaul {}", sendToUser);
                // Se envia al usuario por default
                destinatarios = "sendToUser";
            }

            try {
                mimeMessage = armaMensajeConTextoDeTemplate(destinatarios, "Notificación automática VUCEM-MF", model,
                        "notificacion");
            }
            catch (Exception e) {
                log.error("Error al generar MimeMessage en MailTransformer ", e);
            }

            return mimeMessage;
        }

        private MimeMessage armaMensajeConTextoDeTemplate(String emails, String motivo, Map<String, Object> model,
                String template) throws MessagingException {

            String texto = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template + templateSufijo, "utf-8",
                    model);
            if (log.isDebugEnabled()) {
                log.debug("Texto del e-mail '" + texto + "'");
            }

            return armaMensaje(emails, motivo, texto);
        }

        private MimeMessage armaMensaje(final String emails, final String motivo, final String texto)
                throws MessagingException {

            MimeMessage mensaje = mailSender.createMimeMessage();

            MimeMessageHelper helper = new MimeMessageHelper(mensaje);
            helper.addTo(emails);
            helper.setFrom(from);
            helper.setSubject(motivo);
            boolean isHTML = true;
            helper.setText(texto, isHTML);

            log.debug("Armando mensaje de correo, Para:[{}], De:[{}], Motivo:[{}] Mensaje:[{}]", emails, from, motivo,
                    texto);
            return mensaje;
        }
    }

这里我使用velocity来格式化带有HTML的信息,这会给你一个很棒的外观和感觉。