KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > axis > transport > mail > MailSender


1 /*
2  * Copyright 2001-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.apache.axis.transport.mail;
17
18 import org.apache.axis.AxisFault;
19 import org.apache.axis.Message;
20 import org.apache.axis.MessageContext;
21 import org.apache.axis.components.logger.LogFactory;
22 import org.apache.axis.components.uuid.UUIDGen;
23 import org.apache.axis.components.uuid.UUIDGenFactory;
24 import org.apache.axis.handlers.BasicHandler;
25 import org.apache.axis.transport.http.HTTPConstants;
26 import org.apache.axis.utils.Messages;
27 import org.apache.commons.logging.Log;
28 import org.apache.commons.net.pop3.POP3Client;
29 import org.apache.commons.net.pop3.POP3MessageInfo;
30 import org.apache.commons.net.smtp.SMTPClient;
31 import org.apache.commons.net.smtp.SMTPReply;
32
33 import javax.mail.Session JavaDoc;
34 import javax.mail.internet.InternetAddress JavaDoc;
35 import javax.mail.internet.MimeMessage JavaDoc;
36 import javax.mail.internet.MimePart JavaDoc;
37 import java.io.BufferedReader JavaDoc;
38 import java.io.ByteArrayInputStream JavaDoc;
39 import java.io.ByteArrayOutputStream JavaDoc;
40 import java.io.Reader JavaDoc;
41 import java.io.Writer JavaDoc;
42 import java.util.Properties JavaDoc;
43
44 /**
45  * This is meant to be used on a SOAP Client to call a SOAP server via SMTP/POP3
46  *
47  * @author Davanum Srinivas (dims@yahoo.com)
48  */

49 public class MailSender extends BasicHandler {
50
51     protected static Log log = LogFactory.getLog(MailSender.class.getName());
52     private UUIDGen uuidGen = UUIDGenFactory.getUUIDGen();
53
54     Properties JavaDoc prop = new Properties JavaDoc();
55     Session JavaDoc session = Session.getDefaultInstance(prop, null);
56
57     /**
58      * invoke creates a socket connection, sends the request SOAP message and then
59      * reads the response SOAP message back from the SOAP server
60      *
61      * @param msgContext the messsage context
62      *
63      * @throws AxisFault
64      */

65     public void invoke(MessageContext msgContext) throws AxisFault {
66
67         if (log.isDebugEnabled()) {
68             log.debug(Messages.getMessage("enter00", "MailSender::invoke"));
69         }
70         try {
71             // Send the SOAP request to the SMTP server
72
String JavaDoc id = writeUsingSMTP(msgContext);
73             
74             // Read SOAP response from the POP3 Server
75
readUsingPOP3(id, msgContext);
76         } catch (Exception JavaDoc e) {
77             log.debug(e);
78             throw AxisFault.makeFault(e);
79         }
80         if (log.isDebugEnabled()) {
81             log.debug(Messages.getMessage("exit00",
82                     "HTTPDispatchHandler::invoke"));
83         }
84     }
85
86
87     /**
88      * Send the soap request message to the server
89      *
90      * @param msgContext message context
91      *
92      * @return id for the current message
93      * @throws Exception
94      */

95     private String JavaDoc writeUsingSMTP(MessageContext msgContext)
96             throws Exception JavaDoc {
97         String JavaDoc id = (new java.rmi.server.UID JavaDoc()).toString();
98         String JavaDoc smtpHost = msgContext.getStrProp(MailConstants.SMTP_HOST);
99
100         SMTPClient client = new SMTPClient();
101         client.connect(smtpHost);
102         
103         // After connection attempt, you should check the reply code to verify
104
// success.
105
System.out.print(client.getReplyString());
106         int reply = client.getReplyCode();
107         if (!SMTPReply.isPositiveCompletion(reply)) {
108             client.disconnect();
109             AxisFault fault = new AxisFault("SMTP", "( SMTP server refused connection )", null, null);
110             throw fault;
111         }
112
113         client.login(smtpHost);
114         System.out.print(client.getReplyString());
115         reply = client.getReplyCode();
116         if (!SMTPReply.isPositiveCompletion(reply)) {
117             client.disconnect();
118             AxisFault fault = new AxisFault("SMTP", "( SMTP server refused connection )", null, null);
119             throw fault;
120         }
121
122         String JavaDoc fromAddress = msgContext.getStrProp(MailConstants.FROM_ADDRESS);
123         String JavaDoc toAddress = msgContext.getStrProp(MailConstants.TO_ADDRESS);
124
125         MimeMessage JavaDoc msg = new MimeMessage JavaDoc(session);
126         msg.setFrom(new InternetAddress JavaDoc(fromAddress));
127         msg.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress JavaDoc(toAddress));
128
129         // Get SOAPAction, default to ""
130
String JavaDoc action = msgContext.useSOAPAction()
131                 ? msgContext.getSOAPActionURI()
132                 : "";
133
134         if (action == null) {
135             action = "";
136         }
137
138         Message reqMessage = msgContext.getRequestMessage();
139
140         msg.addHeader(HTTPConstants.HEADER_USER_AGENT, Messages.getMessage("axisUserAgent"));
141         msg.addHeader(HTTPConstants.HEADER_SOAP_ACTION, action);
142         msg.setDisposition(MimePart.INLINE);
143         msg.setSubject(id);
144
145         ByteArrayOutputStream JavaDoc out = new ByteArrayOutputStream JavaDoc(8 * 1024);
146         reqMessage.writeTo(out);
147         msg.setContent(out.toString(), reqMessage.getContentType(msgContext.getSOAPConstants()));
148
149         ByteArrayOutputStream JavaDoc out2 = new ByteArrayOutputStream JavaDoc(8 * 1024);
150         msg.writeTo(out2);
151
152         client.setSender(fromAddress);
153         System.out.print(client.getReplyString());
154         client.addRecipient(toAddress);
155         System.out.print(client.getReplyString());
156
157         Writer JavaDoc writer = client.sendMessageData();
158         System.out.print(client.getReplyString());
159         writer.write(out2.toString());
160         writer.flush();
161         writer.close();
162
163         System.out.print(client.getReplyString());
164         if (!client.completePendingCommand()) {
165             System.out.print(client.getReplyString());
166             AxisFault fault = new AxisFault("SMTP", "( Failed to send email )", null, null);
167             throw fault;
168         }
169         System.out.print(client.getReplyString());
170         client.logout();
171         client.disconnect();
172         return id;
173     }
174
175     /**
176      * Read from server using POP3
177      * @param msgContext
178      * @throws Exception
179      */

180     private void readUsingPOP3(String JavaDoc id, MessageContext msgContext) throws Exception JavaDoc {
181         // Read the response back from the server
182
String JavaDoc pop3Host = msgContext.getStrProp(MailConstants.POP3_HOST);
183         String JavaDoc pop3User = msgContext.getStrProp(MailConstants.POP3_USERID);
184         String JavaDoc pop3passwd = msgContext.getStrProp(MailConstants.POP3_PASSWORD);
185
186         Reader JavaDoc reader;
187         POP3MessageInfo[] messages = null;
188
189         MimeMessage JavaDoc mimeMsg = null;
190         POP3Client pop3 = new POP3Client();
191         // We want to timeout if a response takes longer than 60 seconds
192
pop3.setDefaultTimeout(60000);
193
194         for (int i = 0; i < 12; i++) {
195             pop3.connect(pop3Host);
196
197             if (!pop3.login(pop3User, pop3passwd)) {
198                 pop3.disconnect();
199                 AxisFault fault = new AxisFault("POP3", "( Could not login to server. Check password. )", null, null);
200                 throw fault;
201             }
202
203             messages = pop3.listMessages();
204             if (messages != null && messages.length > 0) {
205                 StringBuffer JavaDoc buffer = null;
206                 for (int j = 0; j < messages.length; j++) {
207                     reader = pop3.retrieveMessage(messages[j].number);
208                     if (reader == null) {
209                         AxisFault fault = new AxisFault("POP3", "( Could not retrieve message header. )", null, null);
210                         throw fault;
211                     }
212
213                     buffer = new StringBuffer JavaDoc();
214                     BufferedReader JavaDoc bufferedReader = new BufferedReader JavaDoc(reader);
215                     int ch;
216                     while ((ch = bufferedReader.read()) != -1) {
217                         buffer.append((char) ch);
218                     }
219                     bufferedReader.close();
220                     if (buffer.toString().indexOf(id) != -1) {
221                         ByteArrayInputStream JavaDoc bais = new ByteArrayInputStream JavaDoc(buffer.toString().getBytes());
222                         Properties JavaDoc prop = new Properties JavaDoc();
223                         Session JavaDoc session = Session.getDefaultInstance(prop, null);
224
225                         mimeMsg = new MimeMessage JavaDoc(session, bais);
226                         pop3.deleteMessage(messages[j].number);
227                         break;
228                     }
229                     buffer = null;
230                 }
231             }
232             pop3.logout();
233             pop3.disconnect();
234             if (mimeMsg == null) {
235                 Thread.sleep(5000);
236             } else {
237                 break;
238             }
239         }
240
241         if (mimeMsg == null) {
242             pop3.logout();
243             pop3.disconnect();
244             AxisFault fault = new AxisFault("POP3", "( Could not retrieve message list. )", null, null);
245             throw fault;
246         }
247
248         String JavaDoc contentType = mimeMsg.getContentType();
249         String JavaDoc contentLocation = mimeMsg.getContentID();
250         Message outMsg = new Message(mimeMsg.getInputStream(), false,
251                 contentType, contentLocation);
252
253         outMsg.setMessageType(Message.RESPONSE);
254         msgContext.setResponseMessage(outMsg);
255         if (log.isDebugEnabled()) {
256             log.debug("\n" + Messages.getMessage("xmlRecd00"));
257             log.debug("-----------------------------------------------");
258             log.debug(outMsg.getSOAPPartAsString());
259         }
260     }
261 }
262
Popular Tags