KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > transport


1 /*
2  * @(#)transport.java 1.12 01/05/23
3  *
4  * Copyright 1997-2000 Sun Microsystems, Inc. All Rights Reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * - Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  *
13  * - Redistribution in binary form must reproduce the above copyright
14  * notice, this list of conditions and the following disclaimer in the
15  * documentation and/or other materials provided with the distribution.
16  *
17  * Neither the name of Sun Microsystems, Inc. or the names of contributors
18  * may be used to endorse or promote products derived from this software
19  * without specific prior written permission.
20  *
21  * This software is provided "AS IS," without a warranty of any kind. ALL
22  * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
23  * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
24  * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND
25  * ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES OR LIABILITIES
26  * SUFFERED BY LICENSEE AS A RESULT OF OR RELATING TO USE, MODIFICATION
27  * OR DISTRIBUTION OF THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL
28  * SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR
29  * FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE
30  * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY,
31  * ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS
32  * BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
33  *
34  * You acknowledge that Software is not designed, licensed or intended
35  * for use in the design, construction, operation or maintenance of any
36  * nuclear facility.
37  */

38
39 import java.util.*;
40 import javax.mail.*;
41 import javax.mail.internet.*;
42 import javax.mail.event.*;
43 import javax.activation.*;
44
45 /**
46  * transport is a simple program that creates a message, explicitly
47  * retrieves a Transport from the session based on the type of the
48  * address (it's InternetAddress, so SMTP will be used) and sends
49  * the message.
50  *
51  * usage: <code>java transport <i>"toaddr1[, toaddr2]*" from smtphost
52  * true|false</i></code><br>
53  * where <i>to</i> and <i>from</i> are the destination and
54  * origin email addresses, respectively, and <i>smtphost</i>
55  * is the hostname of the machine that has the smtp server
56  * running. The <i>to</i> addresses can be either a single email
57  * address or a comma-separated list of email addresses in
58  * quotes, i.e. "joe@machine, jane, max@server.com"
59  * The last parameter either turns on or turns off
60  * debugging during sending.
61  *
62  * @author Max Spivak
63  */

64 public class transport implements ConnectionListener, TransportListener {
65     static String JavaDoc msgText = "This is a message body.\nHere's the second line.";
66     static String JavaDoc msgText2 = "\nThis was sent by transport.java demo program.";
67
68     public static void main(String JavaDoc[] args) {
69     Properties props = new Properties();
70     // parse the arguments
71
InternetAddress[] addrs = null;
72     boolean debug = false;
73     if (args.length != 4) {
74         usage();
75         return;
76     } else {
77         props.put("mail.smtp.user", args[1]);
78         props.put("mail.smtp.host", args[2]);
79         if (args[3].equals("true")) {
80         debug = true;
81         } else if (args[3].equals("false")) {
82         debug = false;
83         } else {
84         usage();
85         return;
86         }
87
88         // parse the destination addresses
89
try {
90         addrs = InternetAddress.parse(args[0], false);
91         } catch (AddressException aex) {
92         System.out.println("Invalid Address");
93         aex.printStackTrace();
94         return;
95         }
96     }
97     // create some properties and get a Session
98
Session session = Session.getInstance(props, null);
99     session.setDebug(debug);
100
101     transport t = new transport();
102     t.go(session, addrs);
103     }
104
105     public transport() {}
106
107     public void go(Session session, InternetAddress[] toAddr) {
108     Transport trans = null;
109
110     try {
111         // create a message
112
Message msg = new MimeMessage(session);
113         msg.setFrom();
114         msg.setRecipients(Message.RecipientType.TO, toAddr);
115         msg.setSubject("JavaMail APIs transport.java Test");
116         msg.setSentDate(new Date()); // Date: header
117
msg.setContent(msgText+msgText2, "text/plain");
118         msg.saveChanges();
119
120         // get the smtp transport for the address
121
trans = session.getTransport(toAddr[0]);
122
123         // register ourselves as listener for ConnectionEvents
124
// and TransportEvents
125
trans.addConnectionListener(this);
126         trans.addTransportListener(this);
127
128         // connect the transport
129
trans.connect();
130
131         // send the message
132
trans.sendMessage(msg, toAddr);
133
134         // give the EventQueue enough time to fire its events
135
try {Thread.sleep(5);}catch(InterruptedException JavaDoc e) {}
136
137     } catch (MessagingException mex) {
138         // give the EventQueue enough time to fire its events
139
try {Thread.sleep(5);}catch(InterruptedException JavaDoc e) {}
140
141         mex.printStackTrace();
142         System.out.println();
143         Exception JavaDoc ex = mex;
144         do {
145         if (ex instanceof SendFailedException) {
146             SendFailedException sfex = (SendFailedException)ex;
147             Address[] invalid = sfex.getInvalidAddresses();
148             if (invalid != null) {
149             System.out.println(" ** Invalid Addresses");
150             if (invalid != null) {
151                 for (int i = 0; i < invalid.length; i++)
152                 System.out.println(" " + invalid[i]);
153             }
154             }
155             Address[] validUnsent = sfex.getValidUnsentAddresses();
156             if (validUnsent != null) {
157             System.out.println(" ** ValidUnsent Addresses");
158             if (validUnsent != null) {
159                 for (int i = 0; i < validUnsent.length; i++)
160                 System.out.println(" "+validUnsent[i]);
161             }
162             }
163             Address[] validSent = sfex.getValidSentAddresses();
164             if (validSent != null) {
165             System.out.println(" ** ValidSent Addresses");
166             if (validSent != null) {
167                 for (int i = 0; i < validSent.length; i++)
168                 System.out.println(" "+validSent[i]);
169             }
170             }
171         }
172         System.out.println();
173         if (ex instanceof MessagingException)
174             ex = ((MessagingException)ex).getNextException();
175         else
176             ex = null;
177         } while (ex != null);
178     } finally {
179         try {
180         // close the transport
181
trans.close();
182         } catch (MessagingException mex) { /* ignore */ }
183     }
184     }
185
186     // implement ConnectionListener interface
187
public void opened(ConnectionEvent e) {
188     System.out.println(">>> ConnectionListener.opened()");
189     }
190     public void disconnected(ConnectionEvent e) {}
191     public void closed(ConnectionEvent e) {
192     System.out.println(">>> ConnectionListener.closed()");
193     }
194
195     // implement TransportListener interface
196
public void messageDelivered(TransportEvent e) {
197     System.out.print(">>> TransportListener.messageDelivered().");
198     System.out.println(" Valid Addresses:");
199     Address[] valid = e.getValidSentAddresses();
200     if (valid != null) {
201         for (int i = 0; i < valid.length; i++)
202         System.out.println(" " + valid[i]);
203     }
204     }
205     public void messageNotDelivered(TransportEvent e) {
206     System.out.print(">>> TransportListener.messageNotDelivered().");
207     System.out.println(" Invalid Addresses:");
208     Address[] invalid = e.getInvalidAddresses();
209     if (invalid != null) {
210         for (int i = 0; i < invalid.length; i++)
211         System.out.println(" " + invalid[i]);
212     }
213     }
214     public void messagePartiallyDelivered(TransportEvent e) {
215     // SMTPTransport doesn't partially deliver msgs
216
}
217
218     private static void usage() {
219     System.out.println("usage: java transport \"<to1>[, <to2>]*\" <from> <smtp> true|false\nexample: java transport \"joe@machine, jane\" senderaddr smtphost false");
220     }
221 }
222
Popular Tags