how to migrate spring mail session jndi xml configuration to java config - java

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?

Finally I got it JNDI Lookup using java configuration.
#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;
}
This above code snippet is equivalent to JNDI Lookup mail xml configuration.
<jee:jndi-lookup id="myMailSession"
jndi-name="java:jboss/mail/Email"
expected-type="javax.mail.Session" />

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.

You can define a #Configuration class and create a bean like this.
#Bean
public JndiObjectFactoryBean myMailSession() {
JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
bean.setJndiName("java:jboss/mail/Email");
return bean;
}
and in the #Bean where you use the jndi object you have to cast it:
Session mailSession = (Session) myMailSession().getObject();

Related

Error occurred while sending email using spring frame work

I'm trying to send an email using spring framework. Im getting the following errors while trying to run the code. I use intellij IDE.
Exception in thread "main" java.lang.IllegalArgumentException: The 'original' message argument cannot be null
at org.springframework.util.Assert.notNull(Assert.java:112)
at org.springframework.mail.SimpleMailMessage.<init>(SimpleMailMessage.java:73)
at com.howtodoinjava.demo.model.SimpleOrderManager.placeOrder(SimpleOrderManager.java:34)
at com.howtodoinjava.demo.model.SimpleOrderManager.main(SimpleOrderManager.java:48)
This is my code
package com.howtodoinjava.demo.model;
//import org.springframework.core.annotation.Order;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
public class SimpleOrderManager {
private MailSender mailSender;
private SimpleMailMessage templateMessage;
//public String order;
//public String customer;
public void setMailSender(MailSender mailSender) {
this.mailSender = mailSender;
}
public void setTemplateMessage(SimpleMailMessage templateMessage) {
this.templateMessage = templateMessage;
}
public void placeOrder() {
// Do the business calculations...
// Call the collaborators to persist the order...
// Create a thread safe "copy" of the template message and customize it
SimpleMailMessage msg = new SimpleMailMessage(this.templateMessage);
msg.setTo("mygmail#gmail.com");
msg.setText("Message");
try{
this.mailSender.send(msg);
}
catch (MailException ex) {
// simply log it and go on...
System.err.println(ex.getMessage());
}
}
public static void main(String []args){
SimpleOrderManager obj = new SimpleOrderManager();
obj.placeOrder();
}
}
I have hard coded the message and email address for now.
edit:
Now I get this error After removing this.templateMessage.
Exception in thread "main" java.lang.NullPointerException
at com.howtodoinjava.demo.model.SimpleOrderManager.placeOrder(SimpleOrderManager.java:32)
at com.howtodoinjava.demo.model.SimpleOrderManager.main(SimpleOrderManager.java:42)
This is my spring-servlet.xml file
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.howtodoinjava.demo" />
<mvc:annotation-driven />
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="mail.mycompany.com"/>
</bean>
<!-- this is a template message that we can pre-load with default state -->
<bean id="templateMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="from" value="customerservice#mycompany.com"/>
<property name="subject" value="Your order"/>
</bean>
<bean id="orderManager" class="com.mycompany.businessapp.support.SimpleOrderManager">
<property name="mailSender" ref="mailSender"/>
<property name="templateMessage" ref="templateMessage"/>
</bean>
Assuming that you're following official Spring tutorial, you forgot to add beans definitions.
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="mail.mycompany.com"/>
</bean>
<!-- this is a template message that we can pre-load with default state -->
<bean id="templateMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="from" value="customerservice#mycompany.com"/>
<property name="subject" value="Your order"/>
</bean>
<bean id="orderManager" class="com.mycompany.businessapp.support.SimpleOrderManager">
<property name="mailSender" ref="mailSender"/>
<property name="templateMessage" ref="templateMessage"/>
</bean>
In your code, this.templateMessage is null which results in exception.
Hope it helps!
You use wrong constructor, use:
SimpleMailMessage msg = new SimpleMailMessage();
instead
SimpleMailMessage msg = new SimpleMailMessage(this.templateMessage);
and you also will need to create mailSender:
private JavaMailSenderImpl createMailSender() {
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setUsername(configuration.getUsername());
javaMailSender.setPassword(configuration.getPassword());
javaMailSender.setHost(configuration.getSmtpHost());
javaMailSender.setPort(configuration.getSmtpPort());
javaMailSender.setDefaultEncoding("UTF-8");
Properties properties = javaMailSender.getJavaMailProperties();
if (StringUtils.isNotEmpty(configuration.getFrom())) {
properties.put("mail.smtp.from", configuration.getFrom());
}
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.socketFactory.port", configuration.getSmtpPort());
properties.put("mail.smtp.socketFactory.fallback", false);
properties.put("mail.smtp.auth", true);
properties.put("mail.smtp.starttls.enable", true);
properties.put("mail.transport.protocol", "smtp");
properties.put("mail.debug", configuration.isDebug());
return javaMailSender;
}
just replace configuration calls, with your values.

How would I create the function for sending an email with the parameters set as String from, String to, String Subject, and String body?

I am trying to create a java batch email program that will send an email to a specific inbox with an excel report attachment. I have the function:
public void sendEmail(String to, String from, String subject, String body)
{
}
I am trying to use Spring, and I'm trying to stick to xml configuration in the appcontext file for now instead of annotations (for learning purposes). I want to inject a static resource which is an excel file, and for learning purposes for this module I am avoiding using FileSystemResource for the attachment per my mentor/teacher. I also don't need the body to say anything. The subject line will be "Report" for dummy purposes. Here is what I have so far, just need the meat of the actual email function that's needed so I could pass the parameters of sendEmail by reference in the main class:
public class SendEmail
{
private JavaMailSender mailSender;
public SendEmail(JavaMailSender ms)
{
this.mailSender = ms;
}
public void sendEmail(String from, String to, String Subject, String body)
{
MimeMessage message = mailSender.createMimeMessage();
try
{
MimeMessageHelper helper = new MimeMessageHelper(message);
helper.setTo("whatever#xyz.com");
helper.setText("Test email!");
mailSender.send(message);
}
catch (MessagingException e)
{
throw new MailParseException(e);
}
}
public void setMailSender(JavaMailSender mailSender)
{
this.mailSender = mailSender;
}
}
This is the applicationContext.xml code:
<?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:context="http://www.springframework.org/schema/context"
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">
<context:component-scan base-package="com.transportation"/>
<bean id = "mailSender" class = "org.springframework.mail.javamail.JavaMailSenderImpl">
<property name = "host" value = "Whatever" />
<property name = "port" value = "25" />
</bean>
<bean id = "sendEmail" class = "com.transportation.email.util.SendEmail">
<constructor-arg ref="mailSender"/>
</bean>
</beans>
Try this one.
public void sendMail(final String messageStr, final boolean isHtml) throws MessagingException {
final MimeMessage message = mailSender.createMimeMessage();
final MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(simpleMailMessage.getFrom());
helper.setTo(simpleMailMessage.getTo());
helper.setCc(simpleMailMessage.getCc());
helper.setSubject(simpleMailMessage.getSubject());
helper.setText(messageStr, isHtml);
helper.addInline("myFile", ResourceUtil.loadResourceAsFileSystemResource("NameOfresource"));
mailSender.send(message);
}
public static FileSystemResource loadResourceAsFileSystemResource(final String fileRoute) {
File file = null;
FileSystemResource fileSystemResource;
try {
file = new ClassPathResource(fileRoute).getFile();
fileSystemResource = new FileSystemResource(file);
}
catch (final IOException e) {
fileSystemResource = null;
}
return fileSystemResource;
}
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.host">${mail.smtp.host}</prop>
<prop key="mail.smtp.port">${mail.smtp.port}</prop>
</props>
</property>
</bean>
<bean id="sfErrorMailSender" class="XXX.MailSender">
<property name="mailSender" ref="mailSender" />
<property name="simpleMailMessage" ref="sfErrorNotificationMailMessage" />
</bean>
<bean id="sfErrorNotificationMailMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="from" value="${mail.message.error.sf.to}" />
<property name="to" value="${mail.message.error.sf.from}" />
<property name="subject" value="${mail.message.error.sf.subject}" />
<property name="text" value="${mail.message.error.sf.body}" />
<property name="cc" value="${mail.message.error.sf.cc}" />
</bean>

JMS - Error adding listener to the MessageConsumer

I'm trying to create a POC for JMS Queue. I used spring mvc controllers as the client to the jms. I get the following error when trying to add asynchronous listeners onto the MessageConsumer object(code snippet). I've read somewhere that the listeners can only be added to the MDB (Message driven beans), is it true?
Setup: Using websphere server bus for JMS. Added jndi for conn factory, destinations etc., for synchronous operation everything is working. But, for asynchronous, this is not working.
Used this for setting up the JMS
[1/28/14 14:38:12:570 CST] 0000005d SystemErr R javax.jms.IllegalStateException: CWSIA0084E: The method MessageConsu
mer.setMessageListener is not permitted in this container.
[1/28/14 14:38:12:572 CST] 0000005d SystemErr R at com.ibm.ws.sib.api.jms.impl.JmsMsgConsumerImpl._setMessageListen
er(JmsMsgConsumerImpl.java:660)
[1/28/14 14:38:12:573 CST] 0000005d SystemErr R at com.ibm.ws.sib.api.jms.impl.JmsMsgConsumerImpl.setMessageListene
r(JmsMsgConsumerImpl.java:609)
CODE:
public void connect(String hostName, String portNumber,
String connectionFactoryString, String consumerJNDIName)
throws Exception {
Hashtable env = new Hashtable();
env.put(Context.PROVIDER_URL, "iiop://" + hostName + ":" + portNumber
+ "");
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.ibm.websphere.naming.WsnInitialContextFactory");
InitialContext initialContext = new InitialContext(env);
ConnectionFactory connectionFactory = (ConnectionFactory) initialContext
.lookup(connectionFactoryString);
connection = connectionFactory.createConnection();
connection.start();
// create destination - JMSQueue
Destination destinationReceiver = (Destination) initialContext
.lookup(consumerJNDIName);
consumerSession = connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);
consumer = consumerSession.createConsumer(destinationReceiver);
consumer.setMessageListener(new MessageListener() { **// ERROR here**
public void onMessage(Message msg) {
try {
System.out.println("received: " + ((TextMessage) msg).getText());
} catch (JMSException ex) {
ex.printStackTrace();
}
}
});
}
To consume messages from Queue you need only MessageListener registered in Spring context.
In web.xml you should register resource reference to JMS resources inside application server:
<resource-ref>
<res-ref-name>jms.jndi.cf.name</res-ref-name>
<res-type>javax.jms.ConnectionFactory</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
<resource-ref>
<res-ref-name>jms.jndi.queue</res-ref-name>
<res-type>javax.jms.Queue</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
Next step is Spring context:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd">
<tx:annotation-driven/>
<context:component-scan base-package="com.jms" />
<!-- Connection Factory -->
<jee:jndi-lookup id="myConnectionFactory" jndi-name="jms.jndi.cf.name" />
<!-- Queue -->
<jee:jndi-lookup id="destination" jndi-name="jms.jndi.queue.name" />
<!-- JMS Destination Resolver -->
<bean id="jmsDestinationResolver" class="org.springframework.jms.support.destination.DynamicDestinationResolver">
</bean>
<!-- JMS Queue Template -->
<bean id="jmsQueueTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory">
<ref bean="myConnectionFactory" />
</property>
<property name="destinationResolver">
<ref bean="jmsDestinationResolver" />
</property>
<property name="pubSubDomain">
<value>false</value>
</property>
<property name="receiveTimeout">
<value>20000</value>
</property>
</bean>
<bean id="messageListener" class="com.jms.JMSMessageListener" />
<!-- Message listener container -->
<bean id="jmsConsumerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="myConnectionFactory" />
<property name="destination" ref="destination" />
<property name="messageListener" ref="messageListener" />
</bean>
</beans>
And the final step is MessageListener:
package com.jms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import javax.jms.BytesMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import java.io.ByteArrayInputStream;
import java.io.StringReader;
public class JMSMessageListener implements MessageListener {
private static final Logger LOGGER = LoggerFactory.getLogger(JMSMessageListener.class);
private static final String ENCODNG = "UTF-8";
#Transactional
public void onMessage(Message message) {
if (message instanceof BytesMessage) {
try {
BytesMessage bytesMessage = (BytesMessage) message;
LOGGER.debug("Receive message from Queue:\n" + bytesMessage);
byte[] data = new byte[(int) bytesMessage.getBodyLength()];
bytesMessage.readBytes(data);
String stringMessagePayload = new String(data, ENCODNG);
LOGGER.debug("Message payload: \n" + stringMessagePayload);
}
} catch (Exception ex) {
LOGGER.error("Error has occured: " + ex);
throw new RuntimeException(ex);
}
} else {
throw new IllegalArgumentException("Message must be of type BytesMessage");
}
}
}
I hope this quick example will help you.

How to make SMTP Server secure using Java

I am building a banking application in Java using Spring framework that involved sending email (using SMTP server) but I heard that it's not secure. So how can I make SMTP secure in Java? Is SSL layer and/or HTTPS connection sufficient? Please help.
Thanks.
Instead of making SMTP secure in your java application you need to make cofiguration changes to your SMTP server so that the server will relay mails only from specific ids and ignore others.
Apparently you can use SMTP over SSL with Spring. Here's the sample:
XML Resource
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailS enderImpl">
<property name="host" value="smtp.gmail.com" />
<property name="port" value="465" />
<property name="protocol" value="smtps" />
<property name="username" value="yourAccount#gmail.com"/>
<property name="password" value="yourPassword"/>
<property name="javaMailProperties">
<props>
<prop key="mail.smtps.auth">true</prop>
<prop key="mail.smtps.starttls.enable">true</prop>
<prop key="mail.smtps.debug">true</prop>
</props>
</property>
</bean>
<bean id="mailMessage" class="org.springframework.mail.SimpleMailMessage" >
<property name="from" value="yourAccount#gmail.com" />
<property name="subject" value="Your Subject" />
</bean>
</beans>
Test Class
package test.mail;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.test.AbstractDependencyInjecti onSpringContextTests;
/**
* MailTest.
* #author jalarcon
*/
public class MailTest extends AbstractDependencyInjectionSpringContextTests {
private MailSender mailSender;
private SimpleMailMessage mailMessage;
/* (non-Javadoc)
* #see org.springframework.test.AbstractSingleSpringConte xtTests#getConfigLocations()
*/
#Override
protected String[] getConfigLocations() {
return new String[] {"/beanDictionary/mail.xml"};
}
public void testSendMail() {
//Create a thread safe "sandbox" of the message
SimpleMailMessage msg = new SimpleMailMessage(this.mailMessage);
msg.setTo("yourAccount#gmail.com");
msg.setText("This is a test");
try{
mailSender.send(msg);
} catch(MailException ex) {
throw new RuntimeException(ex);
}
}
// ---------------------------------------------------------- getters/setters
/**
* #return the mailSender
*/
public MailSender getMailSender() {
return mailSender;
}
/**
* #param mailSender the mailSender to set
*/
public void setMailSender(MailSender mailSender) {
this.mailSender = mailSender;
}
/**
* #return the mailMessage
*/
public SimpleMailMessage getMailMessage() {
return mailMessage;
}
/**
* #param mailMessage the mailMessage to set
*/
public void setMailMessage(SimpleMailMessage mailMessage) {
this.mailMessage = mailMessage;
}
}

velocity null point exception

I want to send mail using velocity templates.
My configuration based on Spring 3.1 documentation.
I have an xml file with configuration:
<?xml version="1.0" encoding="UTF-8"?>
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<bean id="sendMail" class="com.myclass.app.SendMail">
<property name="mailSender" ref="mailSender"/>
<property name="velocityEngine" ref="velocityEngine"/>
</bean>
<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="velocityProperties">
<value>
resource.loader=class
class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
</value>
</property>
</bean>
Then I have class:
#Controller
public class SendMail{
private static final Logger logger = Logger.getLogger(SendMail.class);
private JavaMailSender mailSender;
private VelocityEngine velocityEngine;
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void setVelocityEngine(VelocityEngine velocityEngine) {
this.velocityEngine = velocityEngine;
}
#RequestMapping(value = "/sendEmail", method = RequestMethod.GET)
public #ResponseBody void send(){
sentEmail();
}
private void sentEmail(){
try {
// SimpleMailMessage msg = new SimpleMailMessage(mailMessage);
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message,
true, "UTF-8");
helper.setFrom("from#from.com");
helper.setTo("myEmail");
helper.setSubject("title");
Map map = new HashMap();
map.put("user", "Piotr");
map.put("test", "TEST");
String text1 = VelocityEngineUtils.mergeTemplateIntoString(
velocityEngine, "velocity.vm", map );
logger.info(text1);
String text = "test";
helper.setText(text, true);
mailSender.send(message);
} catch (Exception ex) {
System.out.println(ex.getStackTrace());
System.out.println(ex.getMessage());
}
}
}
my vm file is located in "resources" folder.
And all i receive id "Null point Exception";
The response doesn't give me nothing more.
Do you have any ideas, what to do ?
Your templates can't be in resources, they need to be in the classpath that you can configure in the velocityEngine
in your applicationContext.xml :
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="ADDRESS_OF_YOUR_SMTP_SERVER"/>
<property name="defaultEncoding" value="UTF-8"/>
<property name="port" value="XX_PORT_SERVER"/>
<property name="javaMailProperties">
<props>
<prop key="mail.smtps.auth">false</prop> <!-- depending on your smtp server -->
<prop key="mail.smtp.starttls.enable">false</prop>
</props>
</property>
</bean>
<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean" p:resourceLoaderPath="classpath:META-INF/velocity" />
Don't forget the namespace xmlns:p="http://www.springframework.org/schema/p" to use the properties of the above example.
In your Java class SendMail, don't forget to add the annotation #Autowired :
#Autowired
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
#Autowired
public void setVelocityEngine(VelocityEngine velocityEngine) {
this.velocityEngine = velocityEngine;
}
and finally, to send your email, use the MimeMessagePreparator:
MimeMessagePreparator preparator = new MimeMessagePreparator() {
#Override
public void prepare(MimeMessage mimeMessage) throws Exception {
MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
message.setTo("blabla#test.com");
message.setSubject("Email test");
String text = VelocityEngineUtils.mergeTemplateIntoString(
velocityEngine, template, keywords);
message.setText(text, true);
}
};
//Send email using the autowired mailSender
this.mailSender.send(preparator);

Categories