Spring mail support - no subject - java

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

Related

Message redelivery in Spring with JBOSS

I am using Spring SimpleMessageListenerConatiner where acknowledgement mode is 2 (client acknowledge) and Queue is Solace.
When I am throwing runtime exception from my unit test, means standalone spring config, messages are redelivering without any issue, but same code is not working when I am deploying my application in JBOSS.
public class MyListener implements MessageListener {
public void onMessage(Message message) {
try {
throw new ConnectionException("Error in Connection");
} catch (ConnectionException e) {
LOGGER.error("Throwing exception...");
throw new MyRuntimeException("Throwing exception");
} finally {
LOGGER.info("Done...");
}
}
Spring config is:
<bean id="solaceMessageListener" class="org.springframework.jms.listener.SimpleMessageListenerContainer">
<property name="connectionFactory" ref="solaceConnectionFactory"/>
<property name="destinationName" value="QueueName"/>
<property name="messageListener" ref="myListener"/>
<property name="concurrency" value="1"/>
<property name="destinationResolver" ref="destinationResolver" />
<property name="sessionAcknowledgeMode" value="2"/>
</bean>
Constaint:
1. I cannot use DefaultMessageListenerContainer
2. Session Transacted true is working but we have not to use it.

Spring JDBC Template- Decrypt password

I am using Spring JDBC template for establishing the connection with the database. The password is in the encrypted format and want to decrypt it with the help of JDBC template. In order to implement the same, I came to know that I have to override "DriverManagerDataSource" I tried to implement the same but have not succeeded.
<bean id="dataSource"
class="MyclassName">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
public class MyclassName extends DriverManagerDataSource {
#Override
public String getPassword() {
String password = super.getPassword();
//External API decryption call
EncrypterClassName encrypterClassName = new EncrypterClassName();
return encrypterClassName.decrypt(password);
}
}
I know I have to change the <property name="password" value="${jdbc.password}" to call the class I have implemented but not sure How to do the same.
Thank you.
I've written my own ProperyPlaceholderConfigurer which is invoked whenever a variable has to be replaced.
jdbc.password={base64}yourEncryptedSecret
 
import java.io.IOException;
import sun.misc.BASE64Decoder;
public class PropertyPlaceholderConfigurer
extends org.springframework.beans.factory.config.PropertyPlaceholderConfigurer {
#Override
protected String convertPropertyValue(final String originalValue) {
String cryptString = "{base64}";
if (originalValue.startsWith(cryptString)) {
BASE64Decoder decoder = new BASE64Decoder();
String decodedPassword = null;
try {
decodedPassword = new String(decoder.decodeBuffer(originalValue.substring(cryptString.length())));
} catch (IOException e) {
e.printStackTrace();
}
return decodedPassword;
}
return originalValue;
}
}

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

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

Categories