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.MuleMessage;
10  import org.mule.api.transformer.TransformerException;
11  import org.mule.transformer.AbstractMessageTransformer;
12  import org.mule.transformer.types.DataTypeFactory;
13  import org.mule.transport.email.MailProperties;
14  import org.mule.transport.email.MailUtils;
15  import org.mule.transport.email.SmtpConnector;
16  import org.mule.util.MapUtils;
17  import org.mule.util.StringUtils;
18  import org.mule.util.TemplateParser;
19  
20  import java.util.Calendar;
21  import java.util.Iterator;
22  import java.util.Map;
23  import java.util.Properties;
24  
25  import javax.mail.Message;
26  import javax.mail.internet.MimeMessage;
27  
28  import org.apache.commons.logging.Log;
29  import org.apache.commons.logging.LogFactory;
30  
31  /**
32   * <code>StringToEmailMessage</code> will convert a String to a JavaMail Message,
33   * using the String as the contents. This implementation uses properties on the
34   * transformer to determine the To: and Subject: fields.
35   */
36  public class StringToEmailMessage extends AbstractMessageTransformer
37  {
38      /**
39       * logger used by this class
40       */
41      private final Log logger = LogFactory.getLog(getClass());
42  
43      private TemplateParser templateParser = TemplateParser.createMuleStyleParser();
44  
45      public StringToEmailMessage()
46      {
47          this.registerSourceType(DataTypeFactory.STRING);
48          this.setReturnDataType(DataTypeFactory.create(Message.class));
49      }
50  
51  
52      @Override
53      public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException
54      {
55          String endpointAddress = endpoint.getEndpointURI().getAddress();
56          SmtpConnector connector = (SmtpConnector) endpoint.getConnector();
57          String to = lookupProperty(message, MailProperties.TO_ADDRESSES_PROPERTY, endpointAddress);
58          String cc = lookupProperty(message, MailProperties.CC_ADDRESSES_PROPERTY, connector.getCcAddresses());
59          String bcc = lookupProperty(message, MailProperties.BCC_ADDRESSES_PROPERTY, connector.getBccAddresses());
60          String from = lookupProperty(message, MailProperties.FROM_ADDRESS_PROPERTY, connector.getFromAddress());
61          String replyTo = lookupProperty(message, MailProperties.REPLY_TO_ADDRESSES_PROPERTY, connector.getReplyToAddresses());
62          String subject = lookupProperty(message, MailProperties.SUBJECT_PROPERTY, connector.getSubject());
63          String contentType = lookupProperty(message, MailProperties.CONTENT_TYPE_PROPERTY, connector.getContentType());
64  
65          Properties headers = new Properties();
66          Properties customHeaders = connector.getCustomHeaders();
67  
68          if (customHeaders != null && !customHeaders.isEmpty())
69          {
70              headers.putAll(customHeaders);
71          }
72  
73          Properties otherHeaders = message.getOutboundProperty(MailProperties.CUSTOM_HEADERS_MAP_PROPERTY);
74          if (otherHeaders != null && !otherHeaders.isEmpty())
75          {
76                  //TODO Whats going on here?
77  //                final MuleContext mc = context.getMuleContext();
78  //                for (Iterator iterator = message.getPropertyNames().iterator(); iterator.hasNext();)
79  //                {
80  //                    String propertyKey = (String) iterator.next();
81  //                    mc.getRegistry().registerObject(propertyKey, message.getProperty(propertyKey), mc);
82  //                }
83                  headers.putAll(templateParser.parse(new TemplateParser.TemplateCallback()
84                  {
85                      public Object match(String token)
86                      {
87                          return muleContext.getRegistry().lookupObject(token);
88                      }
89                  }, otherHeaders));
90  
91          }
92  
93          if (logger.isDebugEnabled())
94          {
95              StringBuffer buf = new StringBuffer();
96              buf.append("Constructing email using:\n");
97              buf.append("To: ").append(to);
98              buf.append(", From: ").append(from);
99              buf.append(", CC: ").append(cc);
100             buf.append(", BCC: ").append(bcc);
101             buf.append(", Subject: ").append(subject);
102             buf.append(", ReplyTo: ").append(replyTo);
103             buf.append(", Content type: ").append(contentType);
104             buf.append(", Payload type: ").append(message.getPayload().getClass().getName());
105             buf.append(", Custom Headers: ").append(MapUtils.toString(headers, false));
106             logger.debug(buf.toString());
107         }
108 
109         try
110         {
111             MimeMessage email = new MimeMessage(((SmtpConnector) endpoint.getConnector()).getSessionDetails(endpoint).getSession());
112 
113             email.setRecipients(Message.RecipientType.TO, MailUtils.stringToInternetAddresses(to));
114 
115             // sent date
116             email.setSentDate(Calendar.getInstance().getTime());
117 
118             if (StringUtils.isNotBlank(from))
119             {
120                 email.setFrom(MailUtils.stringToInternetAddresses(from)[0]);
121             }
122 
123             if (StringUtils.isNotBlank(cc))
124             {
125                 email.setRecipients(Message.RecipientType.CC, MailUtils.stringToInternetAddresses(cc));
126             }
127 
128             if (StringUtils.isNotBlank(bcc))
129             {
130                 email.setRecipients(Message.RecipientType.BCC, MailUtils.stringToInternetAddresses(bcc));
131             }
132 
133             if (StringUtils.isNotBlank(replyTo))
134             {
135                 email.setReplyTo(MailUtils.stringToInternetAddresses(replyTo));
136             }
137 
138             email.setSubject(subject, outputEncoding);
139 
140             for (Iterator iterator = headers.entrySet().iterator(); iterator.hasNext();)
141             {
142                 Map.Entry entry = (Map.Entry) iterator.next();
143                 email.setHeader(entry.getKey().toString(), entry.getValue().toString());
144             }
145 
146             setContent(message.getPayload(), email, contentType, message);
147 
148             return email;
149         }
150         catch (Exception e)
151         {
152             throw new TransformerException(this, e);
153         }
154     }
155 
156     /**
157      * Searches in outbound, then invocation scope. If not found, returns a passed in default value.
158      */
159     protected String lookupProperty(MuleMessage message, String propName, String defaultValue)
160     {
161         String value = message.getOutboundProperty(propName);
162         if (value == null)
163         {
164             value = message.getInvocationProperty(propName, defaultValue);
165         }
166         return evaluate(value, message);
167     }
168 
169     public String evaluate(String value, MuleMessage message)
170     {
171         if(value != null && muleContext.getExpressionManager().isExpression(value))
172         {
173             value = (String) muleContext.getExpressionManager().evaluate(value, message);
174         }
175         return value;
176     }
177 
178     protected void setContent(Object payload, Message msg, String contentType, MuleMessage message)
179         throws Exception
180     {
181         msg.setContent(payload, contentType);
182     }
183 
184 }