Java Reference
In-Depth Information
<bean id="mailSender"
class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="session" ref="mailSession" />
</bean>
Defining an E-mail Template
Constructing an e-mail message from scratch in the method body is not efficient because you have to
hard-code the e-mail properties. Also, you may have difficulty in writing the e-mail text in terms of Java
strings. You can consider defining an e-mail message template in the bean configuration file and
construct a new e-mail message from it.
<beans ...>
...
<bean id="copyErrorMailMessage"
class="org.springframework.mail.SimpleMailMessage">
<property name="from" value="system@localhost" />
<property name="to" value="admin@localhost" />
<property name="subject" value="File Copy Error" />
<property name="text">
<value>
<![CDATA[
Dear Administrator,
An error occurred when copying the following file :
Source directory : %s
Destination directory : %s
Filename : %s
]]>
</value>
</property>
</bean>
<bean id="errorNotifier"
class="com.apress.springenterpriserecipes.replicator.EmailErrorNotifier">
<property name="mailSender" ref="mailSender" />
<property name="copyErrorMailMessage" ref="copyErrorMailMessage" />
</bean>
</beans>
Note that in the preceding message text, you include the placeholders %s , which will be replaced by
message parameters through String.format() . Of course, you can also use a powerful templating
language such as Velocity or FreeMarker to generate the message text according to a template. It's also a
good practice to separate mail message templates from bean configuration files.
Each time you send e-mail, you can construct a new SimpleMailMessage instance from this injected
template. Then you can generate the message text using String.format() to replace the %s placeholders
with your message parameters.
package com.apress.springenterpriserecipes.replicator;
...
import org.springframework.mail.SimpleMailMessage;
Search WWH ::




Custom Search