KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mule > providers > email > SmtpMessageDispatcher


1 /*
2  * $Id: SmtpMessageDispatcher.java 3982 2006-11-22 14:28:01Z lajos $
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 MuleSource MPL
7  * license, a copy of which has been included with this distribution in the
8  * LICENSE.txt file.
9  */

10
11 package org.mule.providers.email;
12
13 import java.util.Calendar JavaDoc;
14
15 import javax.mail.Message JavaDoc;
16 import javax.mail.MessagingException JavaDoc;
17 import javax.mail.Session JavaDoc;
18 import javax.mail.Transport JavaDoc;
19 import javax.mail.URLName JavaDoc;
20
21 import org.mule.config.i18n.Messages;
22 import org.mule.providers.AbstractMessageDispatcher;
23 import org.mule.umo.UMOEvent;
24 import org.mule.umo.UMOException;
25 import org.mule.umo.UMOMessage;
26 import org.mule.umo.endpoint.EndpointException;
27 import org.mule.umo.endpoint.UMOEndpointURI;
28 import org.mule.umo.endpoint.UMOImmutableEndpoint;
29 import org.mule.umo.provider.DispatchException;
30 import org.mule.umo.provider.UMOConnector;
31 import org.mule.util.StringUtils;
32
33 /**
34  * <code>SmtpMessageDispatcher</code> will dispatch Mule events as Mime email
35  * messages over an SMTP gateway
36  */

37 public class SmtpMessageDispatcher extends AbstractMessageDispatcher
38 {
39     private final SmtpConnector connector;
40     protected volatile Transport JavaDoc transport;
41     protected volatile Session JavaDoc session;
42
43     public SmtpMessageDispatcher(UMOImmutableEndpoint endpoint)
44     {
45         super(endpoint);
46         this.connector = (SmtpConnector)endpoint.getConnector();
47     }
48
49     protected void doConnect(UMOImmutableEndpoint endpoint) throws Exception JavaDoc
50     {
51         if (transport == null)
52         {
53             UMOEndpointURI uri = endpoint.getEndpointURI();
54
55             // Try to get the properties from the endpoint and use the connector
56
// properties if they are not given.
57

58             String JavaDoc host = uri.getHost();
59             if (host == null)
60             {
61                 host = connector.getHost();
62             }
63
64             int port = uri.getPort();
65             if (port == -1)
66             {
67                 port = connector.getPort();
68             }
69
70             String JavaDoc username = uri.getUsername();
71             if (StringUtils.isBlank(username))
72             {
73                 username = connector.getUsername();
74             }
75
76             String JavaDoc password = uri.getPassword();
77             if (StringUtils.isBlank(password))
78             {
79                 password = connector.getPassword();
80             }
81
82             URLName JavaDoc url = new URLName JavaDoc(connector.getProtocol(), host, port, null, username, password);
83
84             try
85             {
86                 if (logger.isDebugEnabled())
87                 {
88                     logger.debug("Creating mail session, host = " + url.getHost() + ", port = "
89                                     + url.getPort() + ", user = " + url.getUsername() + ", pass = "
90                                     + url.getPassword());
91                 }
92                 session = MailUtils.createMailSession(url, connector);
93                 session.setDebug(logger.isDebugEnabled());
94
95                 transport = session.getTransport(url);
96                 transport.connect(uri.getHost(), uri.getPort(), uri.getUsername(), uri.getPassword());
97             }
98             catch (Exception JavaDoc e)
99             {
100                 throw new EndpointException(
101                     org.mule.config.i18n.Message.createStaticMessage("Unable to connect to mail transport."),
102                     e);
103             }
104         }
105     }
106
107     protected void doDisconnect() throws Exception JavaDoc
108     {
109         try
110         {
111             transport.close();
112         }
113         finally
114         {
115             transport = null;
116             session = null;
117         }
118     }
119
120     /*
121      * (non-Javadoc)
122      *
123      * @see org.mule.providers.UMOConnector#dispatch(java.lang.Object,
124      * org.mule.providers.MuleEndpoint)
125      */

126     public void doDispatch(UMOEvent event)
127     {
128         try
129         {
130             Object JavaDoc data = event.getTransformedMessage();
131
132             if (!(data instanceof Message JavaDoc))
133             {
134                 throw new DispatchException(new org.mule.config.i18n.Message(
135                     Messages.TRANSFORM_X_UNEXPECTED_TYPE_X, data.getClass().getName(),
136                     Message JavaDoc.class.getName()), event.getMessage(), event.getEndpoint());
137             }
138             else
139             {
140                 // Check the message for any unset data and use defaults
141
sendMailMessage((Message JavaDoc)data);
142             }
143         }
144         catch (Exception JavaDoc e)
145         {
146             connector.handleException(e);
147         }
148     }
149
150     /*
151      * (non-Javadoc)
152      *
153      * @see org.mule.umo.provider.UMOConnectorSession#getDelegateSession()
154      */

155     public Object JavaDoc getDelegateSession() throws UMOException
156     {
157         return session;
158     }
159
160     /**
161      * Make a specific request to the underlying transport
162      *
163      * @param endpoint the endpoint to use when connecting to the resource
164      * @param timeout the maximum time the operation should block before returning.
165      * The call should return immediately if there is data available. If
166      * no data becomes available before the timeout elapses, null will be
167      * returned
168      * @return the result of the request wrapped in a UMOMessage object. Null will be
169      * returned if no data was avaialable
170      * @throws Exception if the call to the underlying protocal cuases an exception
171      */

172     protected UMOMessage doReceive(UMOImmutableEndpoint endpoint, long timeout) throws Exception JavaDoc
173     {
174         throw new UnsupportedOperationException JavaDoc("doReceive");
175     }
176
177     protected UMOMessage doSend(UMOEvent event) throws Exception JavaDoc
178     {
179         doDispatch(event);
180         return event.getMessage();
181     }
182
183     protected void sendMailMessage(Message JavaDoc message) throws MessagingException JavaDoc
184     {
185         // sent date
186
message.setSentDate(Calendar.getInstance().getTime());
187
188         // These getAllRecipients() and similar methods always return null???
189
// Seems like JavaMail 1.3.3 is setting headers only
190
// transport.sendMessage(message, message.getAllRecipients());
191

192         // this call at least preserves the TO field
193
// TODO handle CC and BCC
194
Transport.send(message);
195         if (logger.isDebugEnabled())
196         {
197             StringBuffer JavaDoc msg = new StringBuffer JavaDoc(200);
198             msg.append("Email message sent with subject'").append(message.getSubject()).append("' sent- ");
199             msg.append(", From: ").append(MailUtils.mailAddressesToString(message.getFrom())).append(" ");
200             msg.append(", To: ").append(
201                 MailUtils.mailAddressesToString(message.getRecipients(Message.RecipientType.TO))).append(" ");
202             msg.append(", Cc: ").append(
203                 MailUtils.mailAddressesToString(message.getRecipients(Message.RecipientType.CC))).append(" ");
204             msg.append(", Bcc: ")
205                 .append(MailUtils.mailAddressesToString(message.getRecipients(Message.RecipientType.BCC)))
206                 .append(" ");
207             msg.append(", ReplyTo: ").append(MailUtils.mailAddressesToString(message.getReplyTo()));
208
209             logger.debug(msg.toString());
210         }
211
212     }
213
214     /*
215      * (non-Javadoc)
216      *
217      * @see org.mule.umo.provider.UMOConnectorSession#getConnector()
218      */

219     public UMOConnector getConnector()
220     {
221         return connector;
222     }
223
224     protected void doDispose()
225     {
226         session = null;
227     }
228 }
229
Popular Tags