Email enabling Spring Applications.
Using gmail smtp server, JavaMail and Spring IOC, we can quickly put together a simple mail sending application, without any SMTP server installation. Check this out for a detailed description of using gmail as smtp server. Thanks to Enrico for blogging smtp spring configuration.
Assuming you have used Spring before, here is a short tutorial:
- Add mail.jar from JavaMail project to build path.
- In spring bean configuration file add:
1 <bean id=“mailSender” class=“org.springframework.mail.javamail.JavaMailSenderImpl”>
2 <property name=“host” value=“smtp.gmail.com”/>
3 <property name=“username” value=“${gmail_username}”/>
4 <property name=“password” value=“${gmail_password}”/>
5 <property name=“javaMailProperties”>
6 <props>
7 <prop key=“mail.smtp.auth”>true</prop>
8 <prop key=“mail.smtp.starttls.enable”>true</prop>
9 </props>
10 </property>
11 </bean>
12
13 <!– this is a template message that we can pre-load with default state –>
14 <bean id=“templateMessage” class=“org.springframework.mail.SimpleMailMessage”>
15 <!– The from field is overwritten by gmail to your gmail ID. Go to Gmail Account Settings to choose default outgoing mail ID. –>
16 <property name=“from” value=“notify@abcd-xyz.com”/>
17 <property name=“subject” value=“Mail Notification.”/>
18 </bean>
19 - Create a class MailNotifier where you send mails.
1 import org.springframework.mail.MailException;
2 import org.springframework.mail.MailSender;
3 import org.springframework.mail.SimpleMailMessage;
4
5 import com.abcd.beans.Member;
6
7
8 /**
9 * @author gubbi
10 *
11 */
12
13 public class MailNotifier {
14 private MailSender mMailSender;
15 private SimpleMailMessage mTemplateMessage;
16
17
18 public void sendNotification(Member pMember) {
19 SimpleMailMessage message = new SimpleMailMessage(mTemplateMessage);
20
21 message.setText("Dear " + pMember.getFirstName() + ",nSending test notification.");
22 message.setTo(pMember.getEmail());
23
24 try{
25 mMailSender.send(message);
26 }
27 catch(MailException ex) {
28 ex.printStackTrace();
29 }
30 }
31
32
33 /**
34 * @param pMailSender the mailSender to set
35 */
36 public void setMailSender(MailSender pMailSender) {
37 mMailSender = pMailSender;
38 }
39
40
41 /**
42 * @param pTemplateMessage the templateMessage to set
43 */
44 public void setTemplateMessage(SimpleMailMessage pTemplateMessage) {
45 mTemplateMessage = pTemplateMessage;
46 }
47 }
48 - Add spring bean configuration for MailNotifier class:
1 <bean id="mailNotifier" class="com.abcd.modules.MailNotifier">
2 <property name="mailSender" ref="mailSender"/>
3 <property name="templateMessage" ref="templateMessage"/>
4 </bean>
5 - This is it
Check out Spring Reference for details about sending mails with attachments and using html templates for mail content. Let me know other methods of doing the same.

