KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > smtpsend


1 /*
2  * @(#)smtpsend.java 1.5 05/12/09
3  *
4  * Copyright 1997-2005 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.io.*;
40 import java.net.InetAddress JavaDoc;
41 import java.util.Properties JavaDoc;
42 import java.util.Date JavaDoc;
43
44 import javax.mail.*;
45 import javax.mail.internet.*;
46
47 import com.sun.mail.smtp.*;
48
49 /**
50  * Demo app that shows how to construct and send an RFC822
51  * (singlepart) message.
52  *
53  * XXX - allow more than one recipient on the command line
54  *
55  * This is just a variant of msgsend.java that demonstrates use of
56  * some SMTP-specific features.
57  *
58  * @author Max Spivak
59  * @author Bill Shannon
60  */

61
62 public class smtpsend {
63
64     public static void main(String JavaDoc[] argv) {
65     String JavaDoc to, subject = null, from = null,
66         cc = null, bcc = null, url = null;
67     String JavaDoc mailhost = null;
68     String JavaDoc mailer = "smtpsend";
69     String JavaDoc file = null;
70     String JavaDoc protocol = null, host = null, user = null, password = null;
71     String JavaDoc record = null; // name of folder in which to record mail
72
boolean debug = false;
73     boolean verbose = false;
74     boolean auth = false;
75     boolean ssl = false;
76     BufferedReader in =
77             new BufferedReader(new InputStreamReader(System.in));
78     int optind;
79
80     for (optind = 0; optind < argv.length; optind++) {
81         if (argv[optind].equals("-T")) {
82         protocol = argv[++optind];
83         } else if (argv[optind].equals("-H")) {
84         host = argv[++optind];
85         } else if (argv[optind].equals("-U")) {
86         user = argv[++optind];
87         } else if (argv[optind].equals("-P")) {
88         password = argv[++optind];
89         } else if (argv[optind].equals("-M")) {
90         mailhost = argv[++optind];
91         } else if (argv[optind].equals("-f")) {
92         record = argv[++optind];
93         } else if (argv[optind].equals("-a")) {
94         file = argv[++optind];
95         } else if (argv[optind].equals("-s")) {
96         subject = argv[++optind];
97         } else if (argv[optind].equals("-o")) { // originator
98
from = argv[++optind];
99         } else if (argv[optind].equals("-c")) {
100         cc = argv[++optind];
101         } else if (argv[optind].equals("-b")) {
102         bcc = argv[++optind];
103         } else if (argv[optind].equals("-L")) {
104         url = argv[++optind];
105         } else if (argv[optind].equals("-d")) {
106         debug = true;
107         } else if (argv[optind].equals("-v")) {
108         verbose = true;
109         } else if (argv[optind].equals("-A")) {
110         auth = true;
111         } else if (argv[optind].equals("-S")) {
112         ssl = true;
113         } else if (argv[optind].equals("--")) {
114         optind++;
115         break;
116         } else if (argv[optind].startsWith("-")) {
117         System.out.println(
118 "Usage: smtpsend [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]");
119         System.out.println(
120 "\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]");
121         System.out.println(
122 "\t[-f record-mailbox] [-M transport-host] [-d] [-a attach-file]");
123         System.out.println(
124 "\t[-v] [-A] [-S] [address]");
125         System.exit(1);
126         } else {
127         break;
128         }
129     }
130
131     try {
132         if (optind < argv.length) {
133         // XXX - concatenate all remaining arguments
134
to = argv[optind];
135         System.out.println("To: " + to);
136         } else {
137         System.out.print("To: ");
138         System.out.flush();
139         to = in.readLine();
140         }
141         if (subject == null) {
142         System.out.print("Subject: ");
143         System.out.flush();
144         subject = in.readLine();
145         } else {
146         System.out.println("Subject: " + subject);
147         }
148
149         Properties JavaDoc props = System.getProperties();
150         if (mailhost != null)
151         props.put("mail.smtp.host", mailhost);
152         if (auth)
153         props.put("mail.smtp.auth", "true");
154
155         // Get a Session object
156
Session session = Session.getInstance(props, null);
157         if (debug)
158         session.setDebug(true);
159
160         // construct the message
161
Message msg = new MimeMessage(session);
162         if (from != null)
163         msg.setFrom(new InternetAddress(from));
164         else
165         msg.setFrom();
166
167         msg.setRecipients(Message.RecipientType.TO,
168                     InternetAddress.parse(to, false));
169         if (cc != null)
170         msg.setRecipients(Message.RecipientType.CC,
171                     InternetAddress.parse(cc, false));
172         if (bcc != null)
173         msg.setRecipients(Message.RecipientType.BCC,
174                     InternetAddress.parse(bcc, false));
175
176         msg.setSubject(subject);
177
178         String JavaDoc text = collect(in);
179
180         if (file != null) {
181         // Attach the specified file.
182
// We need a multipart message to hold the attachment.
183
MimeBodyPart mbp1 = new MimeBodyPart();
184         mbp1.setText(text);
185         MimeBodyPart mbp2 = new MimeBodyPart();
186         mbp2.attachFile(file);
187         MimeMultipart mp = new MimeMultipart();
188         mp.addBodyPart(mbp1);
189         mp.addBodyPart(mbp2);
190         msg.setContent(mp);
191         } else {
192         // If the desired charset is known, you can use
193
// setText(text, charset)
194
msg.setText(text);
195         }
196
197         msg.setHeader("X-Mailer", mailer);
198         msg.setSentDate(new Date JavaDoc());
199
200         // send the thing off
201
/*
202          * The simple way to send a message is this:
203          *
204         Transport.send(msg);
205          *
206          * But we're going to use some SMTP-specific features for
207          * demonstration purposes so we need to manage the Transport
208          * object explicitly.
209          */

210         SMTPTransport t =
211         (SMTPTransport)session.getTransport(ssl ? "smtps" : "smtp");
212         try {
213         if (auth)
214             t.connect(mailhost, user, password);
215         else
216             t.connect();
217         t.sendMessage(msg, msg.getAllRecipients());
218         } finally {
219         if (verbose)
220             System.out.println("Response: " +
221                         t.getLastServerResponse());
222         t.close();
223         }
224
225         System.out.println("\nMail was sent successfully.");
226
227         // Keep a copy, if requested.
228

229         if (record != null) {
230         // Get a Store object
231
Store store = null;
232         if (url != null) {
233             URLName urln = new URLName(url);
234             store = session.getStore(urln);
235             store.connect();
236         } else {
237             if (protocol != null)
238             store = session.getStore(protocol);
239             else
240             store = session.getStore();
241
242             // Connect
243
if (host != null || user != null || password != null)
244             store.connect(host, user, password);
245             else
246             store.connect();
247         }
248
249         // Get record Folder. Create if it does not exist.
250
Folder folder = store.getFolder(record);
251         if (folder == null) {
252             System.err.println("Can't get record folder.");
253             System.exit(1);
254         }
255         if (!folder.exists())
256             folder.create(Folder.HOLDS_MESSAGES);
257
258         Message[] msgs = new Message[1];
259         msgs[0] = msg;
260         folder.appendMessages(msgs);
261
262         System.out.println("Mail was recorded successfully.");
263         }
264
265     } catch (Exception JavaDoc e) {
266         if (e instanceof SendFailedException) {
267         MessagingException sfe = (MessagingException)e;
268         if (sfe instanceof SMTPSendFailedException) {
269             SMTPSendFailedException ssfe =
270                     (SMTPSendFailedException)sfe;
271             System.out.println("SMTP SEND FAILED:");
272             if (verbose)
273             System.out.println(ssfe.toString());
274             System.out.println(" Command: " + ssfe.getCommand());
275             System.out.println(" RetCode: " + ssfe.getReturnCode());
276             System.out.println(" Response: " + ssfe.getMessage());
277         } else {
278             if (verbose)
279             System.out.println("Send failed: " + sfe.toString());
280         }
281         Exception JavaDoc ne;
282         while ((ne = sfe.getNextException()) != null &&
283             ne instanceof MessagingException) {
284             sfe = (MessagingException)ne;
285             if (sfe instanceof SMTPAddressFailedException) {
286             SMTPAddressFailedException ssfe =
287                     (SMTPAddressFailedException)sfe;
288             System.out.println("ADDRESS FAILED:");
289             if (verbose)
290                 System.out.println(ssfe.toString());
291             System.out.println(" Address: " + ssfe.getAddress());
292             System.out.println(" Command: " + ssfe.getCommand());
293             System.out.println(" RetCode: " + ssfe.getReturnCode());
294             System.out.println(" Response: " + ssfe.getMessage());
295             } else if (sfe instanceof SMTPAddressSucceededException) {
296             System.out.println("ADDRESS SUCCEEDED:");
297             SMTPAddressSucceededException ssfe =
298                     (SMTPAddressSucceededException)sfe;
299             if (verbose)
300                 System.out.println(ssfe.toString());
301             System.out.println(" Address: " + ssfe.getAddress());
302             System.out.println(" Command: " + ssfe.getCommand());
303             System.out.println(" RetCode: " + ssfe.getReturnCode());
304             System.out.println(" Response: " + ssfe.getMessage());
305             }
306         }
307         } else {
308         System.out.println("Got Exception: " + e);
309         if (verbose)
310             e.printStackTrace();
311         }
312     }
313     }
314
315     public static String JavaDoc collect(BufferedReader in) throws IOException {
316     String JavaDoc line;
317     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
318     while ((line = in.readLine()) != null) {
319         sb.append(line);
320         sb.append("\n");
321     }
322     return sb.toString();
323     }
324 }
325
Popular Tags