View Javadoc

1   /*
2    * $Id: SmtpMessageDispatcher.java 10961 2008-02-22 19:01:02Z dfeist $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSource, Inc.  All rights reserved.  http://www.mulesource.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;
12  
13  import org.mule.api.MuleEvent;
14  import org.mule.api.MuleMessage;
15  import org.mule.api.endpoint.EndpointException;
16  import org.mule.api.endpoint.EndpointURI;
17  import org.mule.api.endpoint.OutboundEndpoint;
18  import org.mule.api.transport.DispatchException;
19  import org.mule.config.i18n.CoreMessages;
20  import org.mule.transport.AbstractMessageDispatcher;
21  
22  import java.util.Calendar;
23  
24  import javax.mail.Message;
25  import javax.mail.MessagingException;
26  import javax.mail.Transport;
27  
28  /**
29   * <code>SmtpMessageDispatcher</code> will dispatch Mule events as Mime email
30   * messages over an SMTP gateway.
31   * 
32   * This contains a reference to a transport (and endpoint and connector, via superclasses)
33   */
34  public class SmtpMessageDispatcher extends AbstractMessageDispatcher
35  {
36      private volatile Transport transport;
37  
38      public SmtpMessageDispatcher(OutboundEndpoint endpoint)
39      {
40          super(endpoint);
41      }
42  
43      private SmtpConnector castConnector()
44      {
45          return (SmtpConnector) getConnector();
46      }
47  
48      protected void doConnect() throws Exception
49      {
50          if (transport == null)
51          {
52              try
53              {
54                  transport = castConnector().getSessionDetails(endpoint).newTransport();
55                  EndpointURI uri = endpoint.getEndpointURI();
56                  transport.connect(uri.getHost(), uri.getPort(), uri.getUser(), uri.getPassword());
57              }
58              catch (Exception e)
59              {
60                  throw new EndpointException(
61                      org.mule.config.i18n.MessageFactory.createStaticMessage("Unable to connect to mail transport."),
62                      e);
63              }
64          }
65      }
66  
67      protected void doDisconnect() throws Exception
68      {
69          if (null != transport)
70          {
71              try
72              {
73                  transport.close();
74              }
75              finally
76              {
77                  transport = null;
78              }
79          }
80      }
81  
82      protected void doDispatch(MuleEvent event) throws Exception
83      {
84          Object data = event.transformMessage();
85  
86          if (!(data instanceof Message))
87          {
88              throw new DispatchException(
89                  CoreMessages.transformUnexpectedType(data.getClass(), Message.class),
90                  event.getMessage(), event.getEndpoint());
91          }
92          else
93          {
94              // Check the message for any unset data and use defaults
95              sendMailMessage((Message) data);
96          }
97      }
98  
99      protected MuleMessage doSend(MuleEvent event) throws Exception
100     {
101         doDispatch(event);
102         return null;
103     }
104 
105     protected void sendMailMessage(Message message) throws MessagingException
106     {
107         // sent date
108         message.setSentDate(Calendar.getInstance().getTime());
109 
110         /*
111          * Double check that the transport is still connected as some SMTP servers may 
112          * disconnect idle connections.
113          */
114         if (!transport.isConnected())
115         {
116             EndpointURI uri = endpoint.getEndpointURI();
117             if (logger.isInfoEnabled())
118             {
119                 logger.info("Connection closed by remote server. Reconnecting.");
120             }
121             transport.connect(uri.getHost(), uri.getPort(), uri.getUser(), uri.getPassword());
122         }
123 
124         transport.sendMessage(message, message.getAllRecipients());
125 
126         if (logger.isDebugEnabled())
127         {
128             StringBuffer msg = new StringBuffer();
129             msg.append("Email message sent with subject'").append(message.getSubject()).append("' sent- ");
130             msg.append(", From: ").append(MailUtils.mailAddressesToString(message.getFrom())).append(" ");
131             msg.append(", To: ").append(
132                 MailUtils.mailAddressesToString(message.getRecipients(Message.RecipientType.TO))).append(" ");
133             msg.append(", Cc: ").append(
134                 MailUtils.mailAddressesToString(message.getRecipients(Message.RecipientType.CC))).append(" ");
135             msg.append(", Bcc: ")
136             .append(MailUtils.mailAddressesToString(message.getRecipients(Message.RecipientType.BCC)))
137             .append(" ");
138             msg.append(", ReplyTo: ").append(MailUtils.mailAddressesToString(message.getReplyTo()));
139 
140             logger.debug(msg.toString());
141         }
142 
143     }
144 
145     protected void doDispose()
146     {
147         // nothing doing
148     }
149 
150 }