Subversion Repositories javautils

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
7 daniel-mar 1
/*
2
 * Copyright 1997-2008 Sun Microsystems, Inc. All Rights Reserved.
3
 *
4
 * Redistribution and use in source and binary forms, with or without
5
 * modification, are permitted provided that the following conditions
6
 * are met:
7
 *
8
 *   - Redistributions of source code must retain the above copyright
9
 *     notice, this list of conditions and the following disclaimer.
10
 *
11
 *   - Redistributions in binary form must reproduce the above copyright
12
 *     notice, this list of conditions and the following disclaimer in the
13
 *     documentation and/or other materials provided with the distribution.
14
 *
15
 *   - Neither the name of Sun Microsystems nor the names of its
16
 *     contributors may be used to endorse or promote products derived
17
 *     from this software without specific prior written permission.
18
 *
19
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
20
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
21
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
23
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
 */
31
 
32
import java.io.*;
33
import java.net.InetAddress;
34
import java.util.Properties;
35
import java.util.Date;
36
 
37
import javax.mail.*;
38
import javax.mail.internet.*;
39
 
40
import com.sun.mail.smtp.*;
41
 
42
/**
43
 * Demo app that shows how to construct and send an RFC822
44
 * (singlepart) message.
45
 *
46
 * XXX - allow more than one recipient on the command line
47
 *
48
 * This is just a variant of msgsend.java that demonstrates use of
49
 * some SMTP-specific features.
50
 *
51
 * @author Max Spivak
52
 * @author Bill Shannon
53
 */
54
 
55
public class smtpsend {
56
 
57
    /**
58
     * Example of how to extend the SMTPTransport class.
59
     * This example illustrates how to issue the XACT
60
     * command before the SMTPTransport issues the DATA
61
     * command.
62
     *
63
    public static class SMTPExtension extends SMTPTransport {
64
        public SMTPExtension(Session session, URLName url) {
65
            super(session, url);
66
            // to check that we're being used
67
            System.out.println("SMTPExtension: constructed");
68
        }
69
 
70
        protected synchronized OutputStream data() throws MessagingException {
71
            if (supportsExtension("XACCOUNTING"))
72
                issueCommand("XACT", 250);
73
            return super.data();
74
        }
75
    }
76
     */
77
 
78
    public static void main(String[] argv) {
79
        String  to, subject = null, from = null,
80
                cc = null, bcc = null, url = null;
81
        String mailhost = null;
82
        String mailer = "smtpsend";
83
        String file = null;
84
        String protocol = null, host = null, user = null, password = null;
85
        String record = null;   // name of folder in which to record mail
86
        boolean debug = false;
87
        boolean verbose = false;
88
        boolean auth = false;
89
        String prot = "smtp";
90
        BufferedReader in =
91
                        new BufferedReader(new InputStreamReader(System.in));
92
        int optind;
93
 
94
        /*
95
         * Process command line arguments.
96
         */
97
        for (optind = 0; optind < argv.length; optind++) {
98
            if (argv[optind].equals("-T")) {
99
                protocol = argv[++optind];
100
            } else if (argv[optind].equals("-H")) {
101
                host = argv[++optind];
102
            } else if (argv[optind].equals("-U")) {
103
                user = argv[++optind];
104
            } else if (argv[optind].equals("-P")) {
105
                password = argv[++optind];
106
            } else if (argv[optind].equals("-M")) {
107
                mailhost = argv[++optind];
108
            } else if (argv[optind].equals("-f")) {
109
                record = argv[++optind];
110
            } else if (argv[optind].equals("-a")) {
111
                file = argv[++optind];
112
            } else if (argv[optind].equals("-s")) {
113
                subject = argv[++optind];
114
            } else if (argv[optind].equals("-o")) { // originator
115
                from = argv[++optind];
116
            } else if (argv[optind].equals("-c")) {
117
                cc = argv[++optind];
118
            } else if (argv[optind].equals("-b")) {
119
                bcc = argv[++optind];
120
            } else if (argv[optind].equals("-L")) {
121
                url = argv[++optind];
122
            } else if (argv[optind].equals("-d")) {
123
                debug = true;
124
            } else if (argv[optind].equals("-v")) {
125
                verbose = true;
126
            } else if (argv[optind].equals("-A")) {
127
                auth = true;
128
            } else if (argv[optind].equals("-S")) {
129
                prot = "smtps";
130
            } else if (argv[optind].equals("--")) {
131
                optind++;
132
                break;
133
            } else if (argv[optind].startsWith("-")) {
134
                System.out.println(
135
"Usage: smtpsend [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]");
136
                System.out.println(
137
"\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]");
138
                System.out.println(
139
"\t[-f record-mailbox] [-M transport-host] [-d] [-a attach-file]");
140
                System.out.println(
141
"\t[-v] [-A] [-S] [address]");
142
                System.exit(1);
143
            } else {
144
                break;
145
            }
146
        }
147
 
148
        try {
149
            /*
150
             * Prompt for To and Subject, if not specified.
151
             */
152
            if (optind < argv.length) {
153
                // XXX - concatenate all remaining arguments
154
                to = argv[optind];
155
                System.out.println("To: " + to);
156
            } else {
157
                System.out.print("To: ");
158
                System.out.flush();
159
                to = in.readLine();
160
            }
161
            if (subject == null) {
162
                System.out.print("Subject: ");
163
                System.out.flush();
164
                subject = in.readLine();
165
            } else {
166
                System.out.println("Subject: " + subject);
167
            }
168
 
169
            /*
170
             * Initialize the JavaMail Session.
171
             */
172
            Properties props = System.getProperties();
173
            if (mailhost != null)
174
                props.put("mail." + prot + ".host", mailhost);
175
            if (auth)
176
                props.put("mail." + prot + ".auth", "true");
177
 
178
            /*
179
             * Create a Provider representing our extended SMTP transport
180
             * and set the property to use our provider.
181
             *
182
            Provider p = new Provider(Provider.Type.TRANSPORT, prot,
183
                "smtpsend$SMTPExtension", "JavaMail demo", "no version");
184
            props.put("mail." + prot + ".class", "smtpsend$SMTPExtension");
185
             */
186
 
187
            // Get a Session object
188
            Session session = Session.getInstance(props, null);
189
            if (debug)
190
                session.setDebug(true);
191
 
192
            /*
193
             * Register our extended SMTP transport.
194
             *
195
            session.addProvider(p);
196
             */
197
 
198
            /*
199
             * Construct the message and send it.
200
             */
201
            Message msg = new MimeMessage(session);
202
            if (from != null)
203
                msg.setFrom(new InternetAddress(from));
204
            else
205
                msg.setFrom();
206
 
207
            msg.setRecipients(Message.RecipientType.TO,
208
                                        InternetAddress.parse(to, false));
209
            if (cc != null)
210
                msg.setRecipients(Message.RecipientType.CC,
211
                                        InternetAddress.parse(cc, false));
212
            if (bcc != null)
213
                msg.setRecipients(Message.RecipientType.BCC,
214
                                        InternetAddress.parse(bcc, false));
215
 
216
            msg.setSubject(subject);
217
 
218
            String text = collect(in);
219
 
220
            if (file != null) {
221
                // Attach the specified file.
222
                // We need a multipart message to hold the attachment.
223
                MimeBodyPart mbp1 = new MimeBodyPart();
224
                mbp1.setText(text);
225
                MimeBodyPart mbp2 = new MimeBodyPart();
226
                mbp2.attachFile(file);
227
                MimeMultipart mp = new MimeMultipart();
228
                mp.addBodyPart(mbp1);
229
                mp.addBodyPart(mbp2);
230
                msg.setContent(mp);
231
            } else {
232
                // If the desired charset is known, you can use
233
                // setText(text, charset)
234
                msg.setText(text);
235
            }
236
 
237
            msg.setHeader("X-Mailer", mailer);
238
            msg.setSentDate(new Date());
239
 
240
            // send the thing off
241
            /*
242
             * The simple way to send a message is this:
243
             *
244
            Transport.send(msg);
245
             *
246
             * But we're going to use some SMTP-specific features for
247
             * demonstration purposes so we need to manage the Transport
248
             * object explicitly.
249
             */
250
            SMTPTransport t =
251
                (SMTPTransport)session.getTransport(prot);
252
            try {
253
                if (auth)
254
                    t.connect(mailhost, user, password);
255
                else
256
                    t.connect();
257
                t.sendMessage(msg, msg.getAllRecipients());
258
            } finally {
259
                if (verbose)
260
                    System.out.println("Response: " +
261
                                                t.getLastServerResponse());
262
                t.close();
263
            }
264
 
265
            System.out.println("\nMail was sent successfully.");
266
 
267
            /*
268
             * Save a copy of the message, if requested.
269
             */
270
            if (record != null) {
271
                // Get a Store object
272
                Store store = null;
273
                if (url != null) {
274
                    URLName urln = new URLName(url);
275
                    store = session.getStore(urln);
276
                    store.connect();
277
                } else {
278
                    if (protocol != null)              
279
                        store = session.getStore(protocol);
280
                    else
281
                        store = session.getStore();
282
 
283
                    // Connect
284
                    if (host != null || user != null || password != null)
285
                        store.connect(host, user, password);
286
                    else
287
                        store.connect();
288
                }
289
 
290
                // Get record Folder.  Create if it does not exist.
291
                Folder folder = store.getFolder(record);
292
                if (folder == null) {
293
                    System.err.println("Can't get record folder.");
294
                    System.exit(1);
295
                }
296
                if (!folder.exists())
297
                    folder.create(Folder.HOLDS_MESSAGES);
298
 
299
                Message[] msgs = new Message[1];
300
                msgs[0] = msg;
301
                folder.appendMessages(msgs);
302
 
303
                System.out.println("Mail was recorded successfully.");
304
            }
305
 
306
        } catch (Exception e) {
307
            /*
308
             * Handle SMTP-specific exceptions.
309
             */
310
            if (e instanceof SendFailedException) {
311
                MessagingException sfe = (MessagingException)e;
312
                if (sfe instanceof SMTPSendFailedException) {
313
                    SMTPSendFailedException ssfe =
314
                                    (SMTPSendFailedException)sfe;
315
                    System.out.println("SMTP SEND FAILED:");
316
                    if (verbose)
317
                        System.out.println(ssfe.toString());
318
                    System.out.println("  Command: " + ssfe.getCommand());
319
                    System.out.println("  RetCode: " + ssfe.getReturnCode());
320
                    System.out.println("  Response: " + ssfe.getMessage());
321
                } else {
322
                    if (verbose)
323
                        System.out.println("Send failed: " + sfe.toString());
324
                }
325
                Exception ne;
326
                while ((ne = sfe.getNextException()) != null &&
327
                        ne instanceof MessagingException) {
328
                    sfe = (MessagingException)ne;
329
                    if (sfe instanceof SMTPAddressFailedException) {
330
                        SMTPAddressFailedException ssfe =
331
                                        (SMTPAddressFailedException)sfe;
332
                        System.out.println("ADDRESS FAILED:");
333
                        if (verbose)
334
                            System.out.println(ssfe.toString());
335
                        System.out.println("  Address: " + ssfe.getAddress());
336
                        System.out.println("  Command: " + ssfe.getCommand());
337
                        System.out.println("  RetCode: " + ssfe.getReturnCode());
338
                        System.out.println("  Response: " + ssfe.getMessage());
339
                    } else if (sfe instanceof SMTPAddressSucceededException) {
340
                        System.out.println("ADDRESS SUCCEEDED:");
341
                        SMTPAddressSucceededException ssfe =
342
                                        (SMTPAddressSucceededException)sfe;
343
                        if (verbose)
344
                            System.out.println(ssfe.toString());
345
                        System.out.println("  Address: " + ssfe.getAddress());
346
                        System.out.println("  Command: " + ssfe.getCommand());
347
                        System.out.println("  RetCode: " + ssfe.getReturnCode());
348
                        System.out.println("  Response: " + ssfe.getMessage());
349
                    }
350
                }
351
            } else {
352
                System.out.println("Got Exception: " + e);
353
                if (verbose)
354
                    e.printStackTrace();
355
            }
356
        }
357
    }
358
 
359
    /**
360
     * Read the body of the message until EOF.
361
     */
362
    public static String collect(BufferedReader in) throws IOException {
363
        String line;
364
        StringBuffer sb = new StringBuffer();
365
        while ((line = in.readLine()) != null) {
366
            sb.append(line);
367
            sb.append("\n");
368
        }
369
        return sb.toString();
370
    }
371
}