velocity null point exception - java

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);

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.

Spring Application loads twice

I'm new to Spring and trying to get a example to work. But my application loads twice each time it starts. I think it could be a context problem because of my internet research and I have just one context.xml.
<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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:environment.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="false"/>
</bean>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:environment.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="false"/>
</bean>
<bean name="objectMapper" class="com.fasterxml.jackson.databind.ObjectMapper" />
<bean name="restTemplate" class="org.springframework.web.client.RestTemplate">
<property name="requestFactory" ref="requestFactory" />
</bean>
<bean name="requestFactory" class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
<property name="connectTimeout" value="10000" />
<property name="readTimeout" value="10000" />
</bean>
<bean name="httpClient" class="org.apache.http.client.HttpClient" factory-bean="requestFactory" factory-method="getHttpClient"/>
<bean name="TraderApplication" class="net.mrmoor.TraderApplication"/>
<bean name="API" class="com.iggroup.api.API"/>
<bean name="LightStreamerComponent" class="com.iggroup.api.streaming.LightStreamerComponent"/>
</beans>
My code of the TraderApplication Class is:
... skipped imports ....
#SpringBootApplication
public class TraderApplication implements CommandLineRunner{
private static final Logger log = LoggerFactory.getLogger(TraderApplication.class);
#Autowired
protected ObjectMapper objectMapper;
#Autowired
private API api;
#Autowired
private LightStreamerComponent lightStreamerComponent = new LightStreamerComponent();
private AuthenticationResponseAndConversationContext authenticationContext = null;
private ArrayList<HandyTableListenerAdapter> listeners = new ArrayList<HandyTableListenerAdapter>();
public static void main(String args[]) {
SpringApplication.run(TraderApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
try {
if (args.length < 2) {
log.error("Usage:- Application identifier password apikey");
System.exit(-1);
}
String identifier = args[0];
String password = args[1];
String apiKey = args[2];
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/public-api-client-spring-context.xml");
TraderApplication app = (TraderApplication) applicationContext.getBean("TraderApplication");
app.run(identifier, password, apiKey);
} catch (Exception e) {
log.error("Unexpected error:", e);
}
}
You mention in your comments above you got this working by removing SpringApplication.run(TraderApplication.class, args); but this would be removing spring-boot from your application so I'm going to assume since your question has a tag of [spring-boot] that this is not what you wanted. So here is an alternative way that you can configure beans using your xml.
#ImportResource({"classpath*:public-api-client-spring-context.xml"}) //Proper way to import xml in Spring Boot
#SpringBootApplication
public class TraderApplication implements CommandLineRunner {
...code you had before goes here
#Autowired
TraderApplication app;
#Override
public void run(String... args) throws Exception {
.. your parsing logic here
app.run(identifier, password, apiKey); //Now uses the autowired instance
}
}
You didn't list your pom.xml or build.gradle but it's important to remember that components you have registered in your context xml may be automatically configured in Spring Boot and you may not need to register them yourself in your xml.(Depending on which items you have starters for in your build file)

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>

how to configure a mail server using spring mvc and jsp?

I would just like to ask how can i setup a simple mail server and be able to send an email. Im using apache tomcat 6.0 as my localhost server and spring framework+jsp as well. I'm quite new on this. So if someone can give a nice tutorial, it will be of great help. thanks
Below is how you would get the spring configuration. probably applicationContext-mail.xml. Import that into applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"autowire="byName">
default-autowire="byName">
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="${mail.host}" />
<property name="port" value="${mail.port}" />
<property name="username" value="${mail.username}" />
<property name="password" value="${mail.password}" />
</bean>
<bean id="freemarkerConfiguration"
class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean">
<property name="templateLoaderPath" value="/WEB-INF/templates" />
</bean>
<!-- KINDLY MAINTAIN ALPHABETICAL ORDER THIS LINE ONWARDS -->
<bean id="notificationService" class="com.isavera.service.NotificationServiceImpl"
scope="prototype">
<property name="mailSender" ref="mailSender" />
<property name="freemarkerConfiguration" ref="freemarkerConfiguration" />
<property name="freemarkerTemplate" value="accountInformation.ftl" />
<property name="fromAddress" value="info#apnagenie.com" />
<property name="subject" value="Your account information" />
</bean>
Below is the NotificationServiceImpl
public class NotificationServiceImpl implements NotificationService, Runnable {
private boolean asynchronous = true;
private JavaMailSender mailSender;
private Configuration freemarkerConfiguration;
private String freemarkerTemplate;
private Map<String, Object> attributes;
private String deliveryAddress;
private String[] deliveryAddresses;
private String fromAddress;
private String subject;
private SimpleMailMessage message;
private MimeMessage mimeMessage;
public void deliver() {
message = new SimpleMailMessage();
if (getDeliveryAddresses() == null) {
message.setTo(getDeliveryAddress());
} else {
message.setTo(getDeliveryAddresses());
}
message.setSubject(subject);
message.setFrom(fromAddress);
// Merge the model into the template
final String result;
try {
result = FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfiguration.getTemplate(appendApplicationName(freemarkerTemplate)), attributes);
message.setText(result);
if (asynchronous) {
Thread emailThread = new Thread(this);
emailThread.start();
} else {
run();
}
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
}
}

Spring mail support - no subject

I have updated my libraries, and now e-mails are sent without subject. I don't know where this happened...
Mail API is 1.4.3., Spring 2.5.6. and Spring Integration Mail 1.0.3.RELEASE.
<!-- Definitions for SMTP server -->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="${mail.host}" />
<property name="username" value="${mail.username}" />
<property name="password" value="${mail.password}" />
</bean>
<bean id="adminMailTemplate" class="org.springframework.mail.SimpleMailMessage" >
<property name="from" value="${mail.admin.from}" />
<property name="to" value="${mail.admin.to}" />
<property name="cc">
<list>
<value>${mail.admin.cc1}</value>
</list>
</property>
</bean>
<!-- Mail service definition -->
<bean id="mailService" class="net.bbb.core.service.impl.MailServiceImpl">
<property name="sender" ref="mailSender"/>
<property name="mail" ref="adminMailTemplate"/>
</bean>
And properties mail.host,mail.username,mail.password,mail.admin.from,mail.admin.to,
mail.admin.cc1.
Java class:
/** The sender. */
private MailSender sender;
/** The mail. */
private SimpleMailMessage mail;
public void sendMail() {
this.mail.setSubject("Subject");
this.mail.setText("msg body");
try {
getSender().send(this.mail);
} catch (MailException e) {
log.error("Error sending mail!",e);
}
}
public SimpleMailMessage getMail() {
return this.mail;
}
public void setMail(SimpleMailMessage mail) {
this.mail = mail;
}
public MailSender getSender() {
return this.sender;
}
public void setSender(MailSender mailSender1) {
this.sender = mailSender1;
}
Everything worked before, I am wondering if there may be any conflicts with new libraries.
Finally - I had the time to resolve this.
In pom.xml, I have added java mail dependency and remove exclusion for geronimo javamail in apache axis transport http dependency.
I expect it's something to do with the way that you're injecting a singleton SimpleMailMessage into your bean. This is not thread-safe, since every call to your sendMail method will be using the same underlying SimpleMailmessage object. It's quite possible that some implementation change in the new libraries now means this is broken.
SimpleMailMessage has a copy constructor, so you should do it like this:
<bean id="mailService" class="net.bbb.core.service.impl.MailServiceImpl">
<property name="sender" ref="mailSender"/>
<property name="template" ref="adminMailTemplate"/>
</bean>
and
private SimpleMailMessage template;
public void setTemplate(SimpleMailMessage template) {
this.template = template;
}
public void sendMail() {
SimpleMailMessage message = new SimpleMailMessage(template);
message.setSubject("Subject");
message.setText("msg body");
try {
getSender().send(message);
} catch (MailException e) {
log.error("Error sending mail!",e);
}
}

Categories