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