I'm new to Spring MVC. I've configured a mail session on Wildfly 8.0 Application server. I am using Spring 3.2. I am using a lookup like this:
<jee:jndi-lookup id="myMailSession"
jndi-name="java:jboss/mail/Email"
expected-type="javax.mail.Session" />
However, I am very much stuck trying to figure out how to do this in Java Config . How to migrate this xml based JNDI lookup to java configuration?
You can use spring mail to configure you mail sender
<?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>
And you only need import this config context to your main aplication context.
You will also need example code for use it:
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;
}
}
Here I'm using velocity to format message with HTML, this will give you a great look and feel.