Spring Portlet – Email

The following tutorial, i’ll create a spring portlet with sending email and attachment. Also, include using the application server setup the JNDI mail session.

The tutorial can be divide into 3 part, first part is configure email jndi, second part is upload file and the final part is using spring mail.

The source code and example can download from here.

Setup java mail session in glassfish

  1. D:\Development\glassfish\bin > asadmin create-javamail-resource –mailhost smtp.loongest.com –mailuser no-reply –fromaddress  no-reply@loongest.com mail/LiferayMailSession
  2.  
  3. Command create-javamail-resource executed successfully.

Reference


Create Service Interface

  1. package com.loongest.mail.service;
  2.  
  3. public interface MailService {
  4.  
  5.      public void sendMail(String to, String subject, String body);
  6.  
  7. }

Create Implementation

  1. package com.loongest.mail.service;
  2. import javax.mail.internet.MimeMessage;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.mail.SimpleMailMessage;
  5. import org.springframework.mail.javamail.JavaMailSender;
  6. import org.springframework.mail.javamail.MimeMessageHelper;
  7. import org.springframework.mail.javamail.MimeMessagePreparator;
  8. import org.springframework.stereotype.Service;
  9.  
  10. @Service
  11. public class MailServiceImpl implements MailService {
  12.  
  13.     @Autowired
  14.     private JavaMailSender mailSender;
  15.  
  16.     @Autowired
  17.     private SimpleMailMessage simpleMailMessage;
  18.  
  19.     public void setMailSender(JavaMailSender mailSender) {
  20.         this.mailSender = mailSender;
  21.     }
  22.  
  23.     public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) {
  24.         this.simpleMailMessage = simpleMailMessage;
  25.     }
  26.  
  27.     public void sendMail(final String to,
  28.                          final String subject, final String body) {
  29.  
  30.         MimeMessagePreparator preparator = new MimeMessagePreparator()
  31.         {
  32.             public void prepare(MimeMessage mimeMessage) throws Exception
  33.             {
  34.                  mimeMessage.addHeader("Content-Transfer-Encoding","base64");
  35.                  mimeMessage.setHeader("Content-Disposition", "attachment");
  36.  
  37.                  MimeMessageHelper helper =
  38.                               new MimeMessageHelper(mimeMessage,true, "UTF-8");
  39.  
  40.                  helper.setFrom(simpleMailMessage.getFrom());
  41.                  helper.setTo(to);
  42.                  helper.setSubject(simpleMailMessage.getSubject());
  43.                  helper.setText(body,true);
  44.                 }
  45.         };
  46.         mailSender.send(preparator);
  47.     }
  48. }

Form Object

  1. package com.loongest.mail.model;
  2. import java.io.Serializable;
  3. public class MailForm  implements Serializable {
  4.  
  5.         private static final long serialVersionUID = 1L;
  6.         private String email;
  7.         private String subject;
  8.         private String content;
  9.  
  10.         public MailForm() { }
  11.  
  12.         public String getEmail() {
  13.                 return email;
  14.         }
  15.  
  16.         public void setEmail(String email) {
  17.                 this.email = email;
  18.         }
  19.  
  20.         public String getSubject() {
  21.                 return subject;
  22.         }
  23.  
  24.         public void setSubject(String subject) {
  25.                 this.subject = subject;
  26.         }
  27.  
  28.         public String getContent() {
  29.                 return content;
  30.         }
  31.  
  32.         public void setContent(String content) {
  33.                 this.content = content;
  34.         }
  35. }

Create Controller Class

  1. package com.loongest.mail.controller;
  2. import ….
  3.  
  4. @Controller
  5. @RequestMapping("VIEW")
  6. public class MailController {
  7.  
  8.     @Autowired private MailService mailService;
  9.  
  10.     @RenderMapping
  11.     public String doView(RenderRequest request, RenderResponse response){
  12.         return "view";
  13.     }
  14.  
  15.     @ActionMapping(params = "action=sendmail")
  16.     public void doPost(@ModelAttribute("form") MailForm form,
  17.                            ActionRequest request, ActionResponse response){
  18.  
  19.            mailService.sendMail(form.getEmail(),
  20.                            form.getSubject(),
  21.                            form.getContent());
  22.     }
  23.  
  24.     @ModelAttribute("form")
  25.     public MailForm getCommandObject() {
  26.         return new MailForm();
  27.     }
  28. }

Optional

If you’d like to try out with standard way, you can replace with the following method on action mapping.

  1. @ActionMapping(params = "action=sendmail")
  2. public void doPost2(@ModelAttribute("form") MailForm form,
  3.                  ActionRequest request, ActionResponse response)
  4.               throws NamingException, MessagingException
  5.     {
  6.          InitialContext ic = new InitialContext();
  7.          String name = "java:comp/env/mail/LiferayMailSession";
  8.          Session session = (Session)ic.lookup(name);
  9.  
  10.          Properties props = session.getProperties();
  11.          props.put("mail.from","no-reply@loongest.com");
  12.          Message msg = new MimeMessage(session);
  13.          msg.setSubject(form.getSubject());
  14.          msg.setSentDate(new Date());
  15.          msg.setFrom();
  16.          msg.setRecipients(Message.RecipientType.TO,
  17.                    InternetAddress.parse(form.getEmail(), false));
  18.          msg.setText(form.getContent());
  19.          Transport.send(msg);
  20.     }

Create JSP View

  1.  
  2. <%@ include file="/WEB-INF/jsp/common/includes.jsp" %>
  3. <%@ page import="javax.portlet.PortletURL"%>
  4. <h2> Send mail example</h2>
  5.  
  6. <portlet:actionURL var="mailUrl">
  7.         <portlet:param name="action" value="sendmail" />
  8. </portlet:actionURL>
  9. <form:form name="mailForm" commandName="form" method="post" action="${mailUrl}">       
  10. <table align="left">
  11.         <tr>
  12.                 <td>Send to :</td>
  13.                 <td> <form:input path="email" /> </td>
  14.         </tr>
  15.         <tr>
  16.                 <td>Subject :</td>
  17.                 <td> <form:input path="subject" /> </td>
  18.         </tr>
  19.         <tr>
  20.                 <td>Description :</td>
  21.                 <td> <form:textarea path="content" cols="30" rows="5" /> </td>
  22.         </tr>
  23.         <tr>
  24.                 <td colspan="2"><input type="submit" value="Send Mail 1" /></td>
  25.         </tr>
  26.         <tr>
  27.                 <td colspan="2"> </td>
  28.         </tr>
  29. </table>
  30. </form:form>
  31.  

ApplicationContext

  1.  
  2. <?xml version="1.0" encoding="UTF-8"?>
  3. <beans xmlns="http://www.springframework.org/schema/beans"
  4.         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5.         ……..">
  6.  
  7. <context:property-placeholder location="classpath:mail.properties" />
  8.        
  9. <context:component-scan base-package="com.loongest.mail">
  10.         <context:exclude-filter type="annotation"
  11.                     expression="org.springframework.stereotype.Controller"/>
  12. </context:component-scan>
  13.  
  14. <!–########### Mail Service ###########–>
  15.         
  16. <bean id="mailService" class="com.loongest.mail.service.MailServiceImpl">
  17.         <property name="mailSender" ref="mailSender"/>
  18.         <property name="simpleMailMessage" ref="simpleMailMessage"/>
  19. </bean>
  20.  
  21. <!–########### Mail Sender ###########–>
  22. <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
  23.          <property name="session" ref="mailSession"/>
  24. </bean> 
  25.        
  26. <bean id="mailSession" class="org.springframework.jndi.JndiObjectFactoryBean">
  27.          <property name="jndiName" value="java:comp/env/mail/LiferayMailSession"/>
  28. </bean>
  29.  
  30. <!–########### Template ###########–>
  31. <bean id="simpleMailMessage" class="org.springframework.mail.SimpleMailMessage">       
  32.         <property name="from" value="from@no-spam.com"/>
  33.         <property name="subject" value="No Subject"/>
  34.         <property name="text">
  35.         <value> <![CDATA[
  36.                 Dear Reader,
  37.                
  38.                 Thank you for trying this example.                                                                                     
  39.         ]]>
  40.         </value>
  41.         </property>
  42. </bean>
  43. </beans>

web.xml

  1.    
  2.   <resource-ref>
  3.         <res-ref-name>mail/LiferayMailSession</res-ref-name>
  4.         <res-type>javax.mail.Session</res-type>
  5.         <res-auth>Container</res-auth>
  6.         <res-sharing-scope>Shareable</res-sharing-scope>
  7.     </resource-ref>
  8.  

Troubleshooting

Remember add the above configuration into your web.xml otherwise you will get the error like

  1. Related cause: org.springframework….BeanCreationException:
  2. Error creating bean with name ‘mailSession’ defined in class path resource [applicationContext.xml]:
  3. javax.naming.NameNotFoundException:
  4.                    No object bound to name java:comp/env/mail/LiferayMailSession

Done !

Reference :

http://wheelersoftware.com/articles/spring-javamail.html

http://springtips.blogspot.com/2008/06/send-e-mail-using-spring-and-javamail.html

http://docs.sun.com/source/817-5449/djmail.html

http://docs.sun.com/app/docs/doc/820-4336/beanr?l=en&a=view

http://docs.sun.com/app/docs/doc/820-4335/ablky?l=en&a=view

http://forums.java.net/jive/message.jspa?messageID=366332

https://cejug-classifieds.dev.java.net/source/browse/cejug-classifieds/trunk/cejug-classifieds-login/src/main/java/net/java/dev/cejug/classifieds/login/jms/NotificationMailerBean.java?rev=1326&view=markup

http://picasaweb.google.com/pradyutb/OopPraddy?authkey=Gv1sRgCOKBjZTD9db1bA&feat=directlink#5312016739707868290

http://forums.sun.com/thread.jspa?threadID=668779

http://weblogs.java.net/blog/2008/03/11/resources-glassfish

package com.fsecure.web.ipc.mail;

public interface MailService {

public void sendMail(String from, String subject, String body);

}

You can leave a response, or trackback from your own site.

2 Responses to “Spring Portlet – Email”

  1. Slowa Piosenek says:

    Superb info, I’d say thanks to writer because i have read here many interesting knowledge. Im waiting for more posts. Bye!:)

  2. pobierowo says:

    Thanks For This post, was added to my bookmarks.

Leave a Reply

Security Code: