Spring offers an abstraction layer for sending Emails. Two classes are important. First JavaMailSenderImpl class, which represents the interface to the SMTP server. Additionaly the SimpleMailMessage class, that describes the mail data object. The following example has the use case of sending an Email to the developers, if an exception occurs at order process.
Classes:
public class BagOrderProcess {
private JavaMailSender mailSender;
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
private SimpleMailMessage mailTemplate;
public void setMailTemplate(SimpleMailMessage mailTemplate) {
this.mailTemplate = mailTemplate;
}
public void processOrder(Bag bag) {
try {
// add to persistence layer
} catch (Exception ex) {
//thread safe
SimpleMailMessage mailTemplateTemp = new SimpleMailMessage(this.templateMessage);
this.templateMessage.setText("ERROR: " + ex.getMessage());
this.mailSender.send(mailTemplateTemp);
}
}
}
Spring Instrumentation:
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="smtp.developers-blog.org"/> <property name="username" value="idontknow"/> <property name="password" value="idontknow"/> </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="app@developers-blog.org"/> <property name="to" value="info@developers-blog.org"/> <property name="subject" value="Exception in Order Process"/> </bean> <bean id="orderProcess" class="org.developers.blog.example.spring.mail.BagOrderProcess"> <property name="mailSender" ref="mailSender"/> <property name="templateMessage" ref="templateMessage"/> </bean>Regards
Rafael Sobek
Technorati Tags: Spring Java Mail Spring Mail
