View Javadoc

1   /*
2    * $Id: EmailMessageToString.java 21114 2011-01-26 15:29:13Z aperepel $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.transport.email.transformers;
12  
13  import org.mule.api.transformer.TransformerException;
14  import org.mule.transformer.AbstractDiscoverableTransformer;
15  import org.mule.transformer.types.DataTypeFactory;
16  
17  import javax.mail.BodyPart;
18  import javax.mail.Message;
19  import javax.mail.internet.MimeMultipart;
20  
21  /**
22   * <code>EmailMessageToString</code> extracts the text body of java mail Message and
23   * returns a string. If there is no text body then an empty string is returned.
24   */
25  public class EmailMessageToString extends AbstractDiscoverableTransformer
26  {
27  
28      public EmailMessageToString()
29      {
30          registerSourceType(DataTypeFactory.create(Message.class));
31          setReturnDataType(DataTypeFactory.STRING);
32      }
33  
34      @Override
35      public Object doTransform(Object src, String outputEncoding) throws TransformerException
36      {
37          Message msg = (Message) src;
38          try
39          {
40              /*
41               * Other information about the message such as cc addresses, attachments
42               * are handled by the mail mule message factory.
43               */
44  
45              // For this impl we just pass back the email content
46              Object result = msg.getContent();
47              if (result instanceof String)
48              {
49                  return result;
50              }
51              else if (result instanceof MimeMultipart)
52              {
53                  // very simplistic, only gets first part
54                  BodyPart firstBodyPart = ((MimeMultipart) result).getBodyPart(0);
55                  if (firstBodyPart != null && firstBodyPart.getContentType().startsWith("text/"))
56                  {
57                      Object content = firstBodyPart.getContent();
58                      if (content instanceof String)
59                      {
60                          return content;
61                      }
62                  }
63              }
64              // No text content found either in message or in first body part of
65              // MultiPart content
66              return "";
67          }
68          catch (Exception e)
69          {
70              throw new TransformerException(this, e);
71          }
72      }
73  
74  }