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.example.geomail.components;
8   
9   import org.mule.DefaultMuleMessage;
10  import org.mule.api.DefaultMuleException;
11  import org.mule.api.MuleEventContext;
12  import org.mule.api.MuleMessage;
13  import org.mule.api.lifecycle.Callable;
14  
15  import java.util.ArrayList;
16  import java.util.HashMap;
17  import java.util.List;
18  import java.util.Map;
19  import java.util.regex.Matcher;
20  import java.util.regex.Pattern;
21  
22  import javax.mail.Message;
23  
24  /**
25   * TODO
26   */
27  public class Mail implements Callable
28  {
29      public Object onCall(MuleEventContext eventContext) throws Exception {
30  
31          MuleMessage message = eventContext.getMessage();
32  
33          Message mail = (Message) message.getPayload();
34  
35          String from = mail.getFrom()[0].toString();
36          String[] received = mail.getHeader("Received");
37  
38          List<String> list = new ArrayList<String>();
39  
40          for (int i = received.length - 1; i >= 0; i--) 
41          {
42              ReceivedHeader receivedHeader = ReceivedHeader.getInstance(received[i]);
43              if (receivedHeader != null && receivedHeader.getFrom() != null) 
44              {
45                  if (!receivedHeader.getFrom().startsWith("localhost") && !receivedHeader.getFrom().startsWith("127.0.0.1")) 
46                  {
47                      String ip = getFromIP(receivedHeader);
48  
49                      if (ip != null) 
50                      {
51                          list.add(ip);
52                      }
53                  }
54              }
55          }
56  
57          if (list.isEmpty()) 
58          {
59              throw new DefaultMuleException("Received e-mail does not provide sender IP information.");
60          }
61  
62          Map<String, Object> properties = new HashMap<String, Object>();
63          properties.put("from.email.address", from);
64  
65          MuleMessage result = new DefaultMuleMessage(list, properties, eventContext.getMuleContext());
66          return result;
67      }
68  
69      private String getFromIP(ReceivedHeader receivedHeader) 
70      {
71          String result = null;
72  
73          Matcher matcher = Pattern.compile(".*\\(.*\\[(.*?)\\]\\)", Pattern.DOTALL).matcher(receivedHeader.getFrom());
74          if (matcher.matches()) 
75          {
76              result = matcher.group(1);
77          }
78  
79          return result;
80      }
81  }