Sometimes the e-mail you want to send fits inside a standard template (e.g., maybe it always has the same sender, or maybe the same recipient, or whatever). You can define a template using Spring. Here's an example:
Spring app context config file
<!-- Mail message -->
<bean id="mailMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="from">
<value><![CDATA[Simple Application Monitor <noreply@somehost.com>]]></value>
</property>
<property name="to">
<value><![CDATA[System Administrator <sysadmin@somehost.com>]]></value>
</property>
<property name="subject" value="SAM Alert"/>
</bean>
You can include as many e-mail templates in a Spring app context configuration, including none if you don't need a template. Here I've defined a template that specifies a "from" field, a "to" field and a "subject" field. It doesn't specify the date or the body. That template works say for an application monitoring system but it wouldn't work for an e-commerce site's order confirmation e-mail, which would need to have a variable "to" field.
IMPORTANT: I didn't show it above, but you will need to inject any e-mail templates (i.e. mail messages) you create into your mail-sending service bean. Otherwise the service bean has no way to use the template.
So that's that. Time for the Java code that actually sends the e-mail.
It turns out that the coding part is much simpler than the
configuration (not that the config was too bad). Let's suppose for
the sake of example that we want to send an e-mail based on the
template that we defined above, and that you've injected that template
into your service bean as mailMessage. Then here's the
service bean code that allows you to use the template to send an
e-mail:
Your service bean
SimpleMailMessage message = new SimpleMailMessage(mailMessage);
message.setSentDate(new Date());
message.setText("Blah blah blah...");
mailSender.send(message);
You can see we're creating a new message based on the
mailMessage e-mail template and mailSender
that we injected into said service bean.
And that's it! Not too painful, right?