Sunday, September 20, 2015

WSO2 ESB Sending Mails With Multiple Attachments

WSO2 ESB is mainly used for message mediation purposes.  It supports message routing, inter-mediation, transformation, logging, load balancing, failover routing, task scheduling, Eventing and much more.

There may be special cases where we need to implement business logic in the ESB even though it is not the ESB's task. Lets think we want to send emails with many attachments. So we have to implement business logic in ESB to do this right.

How can we send mails with multiple attachments?  I found TWO ways to do this.

  1. Use gmail connector
  2. Use own class mediator
You can find details about the gmail connector from the official wso2 documentation so I think you can easily catch the usage of it.

In this post I'm going to explain how we can use own class mediator to send mails with multiple attachments. So in this case you can use any mail service provide like yahoo, gmail etc.

So this is the sample class which uses to send mails with multiple attachments.
Note - this class depends on java-mail-1.4 so you have download and import to the project.
 import java.io.IOException;  
 import java.util.Date;  
 import java.util.Properties;  
 import javax.mail.Authenticator;  
 import javax.mail.Message;  
 import javax.mail.MessagingException;  
 import javax.mail.Multipart;  
 import javax.mail.PasswordAuthentication;  
 import javax.mail.Session;  
 import javax.mail.Transport;  
 import javax.mail.internet.AddressException;  
 import javax.mail.internet.InternetAddress;  
 import javax.mail.internet.MimeBodyPart;  
 import javax.mail.internet.MimeMessage;  
 import javax.mail.internet.MimeMultipart;  
 /*  
  * Create connection with the relevant SMTP server.  
  * Create new email with message body part and attachments(multi-parts)  
  * Send email to the address endpoint  
 */  
 public class EmailAttachmentSender extends AbstractMediator {  
      private String host; // smtp server address  
      private String port; // smtp port no  
      private String userName; // sender mail address  
      private String password; // sender password  
      private String toAddress; // receiver mail address  
      private String subject; // mail subject  
      private String message; // email message body   
      private String files; // files URI   
      public boolean mediate(MessageContext context) {  
           try {  
                sendMailWithAttachment(context);  
                System.out.println("message sent");  
           } catch (AddressException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
                System.out.println("message not sent");  
                System.out.println(e.toString());  
           } catch (MessagingException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
                System.out.println("message not sent");  
                System.out.println(e.toString());  
           } catch (Exception e) {  
                e.printStackTrace();  
                System.out.println("message not sent");  
                System.out.println(e.toString());  
           }  
           return true;  
      }  
      private void sendMailWithAttachment(MessageContext mc)  
                throws AddressException, MessagingException {  
           // sets SMTP server properties  
           Properties properties = new Properties();  
           properties.put("mail.smtp.host", host);  
           properties.put("mail.smtp.port", port);  
           properties.put("mail.smtp.auth", "true");  
           properties.put("mail.smtp.starttls.enable", "true");  
           properties.put("mail.user", userName);  
           properties.put("mail.password", password);  
           // creates a new session with an authenticator  
           Authenticator auth = new Authenticator() {  
                public PasswordAuthentication getPasswordAuthentication() {  
                     return new PasswordAuthentication(userName, password);  
                }  
           };  
           Session session = Session.getInstance(properties, auth);  
           // creates a new e-mail message  
           Message msg = new MimeMessage(session);  
           msg.setFrom(new InternetAddress(userName));  
           InternetAddress[] toAddresses = { new InternetAddress(toAddress) };  
           msg.setRecipients(Message.RecipientType.TO, toAddresses);  
           msg.setSubject(subject);  
           msg.setSentDate(new Date());  
           // creates message part  
           MimeBodyPart messageBodyPart = new MimeBodyPart();  
           messageBodyPart.setContent(message, "text/html");  
           // creates multi-part  
           Multipart multipart = new MimeMultipart();  
           multipart.addBodyPart(messageBodyPart);  
           //adding file URIs to the array  
           String[] attachFiles = files.split(",");  
           for (String string : attachFiles) {  
                System.out.println(string);  
           }  
           // adds attachments  
           if (attachFiles != null && attachFiles.length > 0) {  
                for (String filePath : attachFiles) {  
                     MimeBodyPart attachPart = new MimeBodyPart();  
                     try {  
                          attachPart.attachFile(filePath);  
                     } catch (IOException ex) {  
                          ex.printStackTrace();  
                     }  
                     multipart.addBodyPart(attachPart);  
                }  
           }  
           // sets the multi-part as e-mail's content  
           msg.setContent(multipart);  
           // sends the e-mail  
           Transport.send(msg);  
      }  
      public String getHost() {  
           return host;  
      }  
      public void setHost(String host) {  
           this.host = host;  
      }  
      public String getPort() {  
           return port;  
      }  
      public void setPort(String port) {  
           this.port = port;  
      }  
      public String getUserName() {  
           return userName;  
      }  
      public void setUserName(String userName) {  
           this.userName = userName;  
      }  
      public String getPassword() {  
           return password;  
      }  
      public void setPassword(String password) {  
           this.password = password;  
      }  
      public String getToAddress() {  
           return toAddress;  
      }  
      public void setToAddress(String toAddress) {  
           this.toAddress = toAddress;  
      }  
      public String getSubject() {  
           return subject;  
      }  
      public void setSubject(String subject) {  
           this.subject = subject;  
      }  
      public String getMessage() {  
           return message;  
      }  
      public void setMessage(String message) {  
           this.message = message;  
      }  
      public String getFiles() {  
           return files;  
      }  
      public void setFiles(String files) {  
           this.files = files;  
      }  
 }  


Let see the java source code and understand what's going on as a summarize. First, make a connection with the SMTP server and create the new email message according to variable values. (These values can be defined as properties inside class mediator in synapse config.)
Then set the message body as multipart and added the message body part (text message). After that, create the mime body part and add files to it (can add multiple files). Finally, add the mime body part to the message body and send the mail using created connection.
In order to setup this class mediator, you can simply add the EmailSendMediator.jar (you have to build the source project and get the jar file) and java-mail-1.4.jar into [ESB_HOME]\repository\components\lib and restart the server.

You can add a proxy service with the class mediator. Following is a sample proxy service.

 <?xml version="1.0" encoding="UTF-8"?>  
 <proxy xmlns="http://ws.apache.org/ns/synapse"  
     name="customProxy"  
     transports="https,http"  
     statistics="disable"  
     trace="disable"  
     startOnLoad="true">  
   <target>  
    <inSequence>  
      <log level="full"/>  
      <class name="com.wso2.test.EmailAttachmentSender">  
       <property name="port" value="587"/>  
       <property name="message" value="I have some attachments for you."/>  
       <property name="host" value="smtp.gmail.com"/>  
       <property name="subject" value="New email with attachments"/>  
       <property name="userName" value="user@gmail.com"/>  
       <property name="password" value="password"/>  
       <property name="toAddress" value="receiver@gmail.com"/>  
                <property name="files" value="C:/Demo/File/In/a.xml,C:/Demo/File/In/excel.xls,C:/Demo/File/In/pdf-sample.pdf,C:/Demo/File/In/formHTML.html"/>  
      </class>  
      <log level="full"/>  
      <drop/>  
    </inSequence>  
    <outSequence/>  
   </target>  
   <description/>  
 </proxy>  
You can just trigger this service by sending request and you can see the message has been sent successfully.



No comments :

Post a Comment