View Javadoc

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