KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > SimpleSMTP


1 /* ***** BEGIN LICENSE BLOCK *****
2  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
3  *
4  * The contents of this file are subject to the Mozilla Public License Version
5  * 1.1 (the "License"); you may not use this file except in compliance with
6  * the License. You may obtain a copy of the License at
7  * http://www.mozilla.org/MPL/
8  *
9  * Software distributed under the License is distributed on an "AS IS" basis,
10  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
11  * for the specific language governing rights and limitations under the
12  * License.
13  *
14  * The Original Code is Ristretto Mail API.
15  *
16  * The Initial Developers of the Original Code are
17  * Timo Stich and Frederik Dietz.
18  * Portions created by the Initial Developers are Copyright (C) 2004
19  * All Rights Reserved.
20  *
21  * Contributor(s):
22  *
23  * Alternatively, the contents of this file may be used under the terms of
24  * either the GNU General Public License Version 2 or later (the "GPL"), or
25  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
26  * in which case the provisions of the GPL or the LGPL are applicable instead
27  * of those above. If you wish to allow use of your version of this file only
28  * under the terms of either the GPL or the LGPL, and not to allow others to
29  * use your version of this file under the terms of the MPL, indicate your
30  * decision by deleting the provisions above and replace them with the notice
31  * and other provisions required by the GPL or the LGPL. If you do not delete
32  * the provisions above, a recipient may use your version of this file under
33  * the terms of any one of the MPL, the GPL or the LGPL.
34  *
35  * ***** END LICENSE BLOCK ***** */

36 package SimpleSMTP;
37
38 import java.io.File JavaDoc;
39 import java.io.IOException JavaDoc;
40 import java.io.InputStream JavaDoc;
41 import java.net.InetAddress JavaDoc;
42 import java.nio.charset.Charset JavaDoc;
43
44 import org.columba.ristretto.auth.AuthenticationException;
45 import org.columba.ristretto.auth.AuthenticationFactory;
46 import org.columba.ristretto.auth.NoSuchAuthenticationException;
47 import org.columba.ristretto.composer.MimeTreeRenderer;
48 import org.columba.ristretto.io.CharSequenceSource;
49 import org.columba.ristretto.io.FileSource;
50 import org.columba.ristretto.log.RistrettoLogger;
51 import org.columba.ristretto.message.Address;
52 import org.columba.ristretto.message.BasicHeader;
53 import org.columba.ristretto.message.Header;
54 import org.columba.ristretto.message.LocalMimePart;
55 import org.columba.ristretto.message.MimeHeader;
56 import org.columba.ristretto.message.MimeType;
57 import org.columba.ristretto.parser.AddressParser;
58 import org.columba.ristretto.parser.ParserException;
59 import org.columba.ristretto.smtp.SMTPException;
60 import org.columba.ristretto.smtp.SMTPProtocol;
61
62 /**
63  * This is a simple command line smtp client. It shows the usage of the
64  * Ristretto SMTP capabilities.
65  */

66 public class SimpleSMTP {
67
68     private static final String JavaDoc helpMessage =
69         "Usage : SimpleSMTP smtp-server from-address to-address subject [optional args]\n\n"
70             + "Example: SimpleSMTP smtp.test.com sender@test.com example@test.com \"This is a test message\" --text \"Hello, World!\"\n\n"
71             + "--body\t\tMessage String\n"
72             + "--textfile\tMessage from a text file\n"
73             + "--attachment\tFile Attachment\n"
74             + "--auth\t\tusername password\n"
75             + "--help\t\tShow this help screen\n";
76
77     /**
78      *
79      * @param args
80      */

81     public static void main(String JavaDoc[] args) {
82         if (args.length < 4 || args[0].equals("--help")) {
83             System.out.println(helpMessage);
84             return;
85         }
86
87         String JavaDoc smtpServer = args[0];
88
89         // Parse and check the given to- and from-address
90
Address JavaDoc fromAddress;
91         try {
92             fromAddress = AddressParser.parseAddress(args[1]);
93         } catch (ParserException e) {
94             System.err.println("Invalid from-address : " + e.getSource());
95             return;
96         }
97
98         Address JavaDoc toAddress;
99         try {
100             toAddress = AddressParser.parseAddress(args[2]);
101         } catch (ParserException e) {
102             System.err.println("Invalid to-address : " + e.getSource());
103             return;
104         }
105
106         String JavaDoc subject = args[3];
107
108         String JavaDoc body = "Hello, World!";
109         String JavaDoc textfile = null;
110         String JavaDoc attachment = null;
111         String JavaDoc user = null;
112         String JavaDoc password = null;
113         boolean verbose = false;
114
115         // Initialize optional arguments
116

117         for (int i = 4; i < args.length;) {
118             if (args[i].equals("--body")) {
119                 body = args[i + 1];
120                 i += 2;
121             } else if (args[i].equals("--textfile")) {
122                 textfile = args[i + 1];
123                 i += 2;
124             } else if (args[i].equals("--attachment")) {
125                 attachment = args[i + 1];
126                 i += 2;
127             } else if (args[i].equals("--auth")) {
128                 user = args[i + 1];
129                 password = args[i + 2];
130                 i += 3;
131             } else if (args[i].equals("--verbose")) {
132                 verbose = true;
133                 i++;
134             }
135         }
136
137         // If verbose log IO to System.out
138
// Note: This might also be e.g. a filestream to log to a file
139
if (verbose) {
140             RistrettoLogger.setLogStream(System.out);
141         }
142
143         // First we compose the message and then we connect to the SMTP
144
// server to send it.
145

146         // PART 1 : Composing a message
147

148         // Header is the actual header while BasicHeader wraps
149
// a Header object to give easy access to the Header.
150
Header header = new Header();
151         BasicHeader basicHeader = new BasicHeader(header);
152
153         // Add the fields to the header
154
// Note that the basicHeader is only a convienience wrapper
155
// for our header object.
156
basicHeader.setFrom(fromAddress);
157         basicHeader.setTo(new Address JavaDoc[] { toAddress });
158         basicHeader.setSubject(subject, Charset.forName("ISO-8859-1"));
159         basicHeader.set("X-Mailer", "SimpleSMTP example / Ristretto API");
160
161         // Now a mimepart is prepared which actually holds the message
162
// The mimeHeader is another convienice wrapper for the header
163
// object
164
MimeHeader mimeHeader = new MimeHeader(header);
165         mimeHeader.set("Mime-Version", "1.0");
166         LocalMimePart root = new LocalMimePart(mimeHeader);
167
168         LocalMimePart textPart;
169
170         // If we have an attachment we must compose a multipart message
171
if (attachment == null) {
172             textPart = root;
173         } else {
174             mimeHeader.setMimeType(new MimeType("multipart", "mixed"));
175
176             textPart = new LocalMimePart(new MimeHeader());
177             root.addChild(textPart);
178         }
179
180         // Now we can add some message text
181
MimeHeader textHeader = textPart.getHeader();
182         textHeader.setMimeType(new MimeType("text", "plain"));
183         if (body != null) {
184
185             // a simple string
186
root.setBody(new CharSequenceSource(body));
187         } else if (textfile != null) {
188
189             // or a text file
190
try {
191                 root.setBody(new FileSource(new File JavaDoc(textfile)));
192             } catch (IOException JavaDoc e1) {
193                 System.err.println(e1.getLocalizedMessage());
194                 return;
195             }
196         }
197
198         
199         // Now we compose the attachment
200
if (attachment != null) {
201             MimeHeader attachmentHeader =
202                 new MimeHeader("application", "octet-stream");
203             attachmentHeader.setContentTransferEncoding("base64");
204             attachmentHeader.putDispositionParameter("filename", attachment);
205             
206             LocalMimePart attachmentPart = new LocalMimePart(attachmentHeader);
207             try {
208                 attachmentPart.setBody(new FileSource(new File JavaDoc(attachment)));
209             } catch (IOException JavaDoc e1) {
210                 System.err.println(e1.getLocalizedMessage());
211                 return;
212             }
213             root.addChild(attachmentPart);
214         }
215         
216         InputStream JavaDoc messageSource;
217         try {
218             // Finally we render the message to an inputstream
219
messageSource = MimeTreeRenderer.getInstance().renderMimePart( root );
220         } catch (Exception JavaDoc e2) {
221             System.err.println(e2.getLocalizedMessage());
222             return;
223         }
224         
225         
226         // Part 2 : Sending the message
227

228         //Construct the proctol that is bound to the SMTP server
229
SMTPProtocol protocol = new SMTPProtocol(smtpServer);
230         try {
231             // Open the port
232
protocol.openPort();
233             
234             // The EHLO command gives us the capabilities of the server
235
String JavaDoc capabilities[] = protocol.ehlo(InetAddress.getLocalHost());
236             
237             // Authenticate
238
if(user != null ) {
239                 String JavaDoc authCapability = null;
240                 for( int i=0; i<capabilities.length; i++) {
241                     if( capabilities[i].startsWith("AUTH")) {
242                         authCapability = capabilities[i];
243                         break;
244                     }
245                 }
246                 if( authCapability != null ) {
247                     try {
248                         protocol.auth( AuthenticationFactory.getInstance().getSecurestMethod( authCapability ), user, password.toCharArray() );
249                     } catch (NoSuchAuthenticationException e3) {
250                         System.err.println(e3.getLocalizedMessage());
251                         return;
252                     } catch ( AuthenticationException e ) {
253                         System.err.println(e.getMessage());
254                         return;
255                         
256                     }
257                 } else {
258                     System.err.println("Server does not support Authentication!");
259                     return;
260                 }
261                
262             }
263             
264             // Setup from and recipient
265
protocol.mail(fromAddress);
266             protocol.rcpt(toAddress);
267             
268             // Finally send the data
269
protocol.data(messageSource);
270             
271             // And close the session
272
protocol.quit();
273             
274         } catch (IOException JavaDoc e1) {
275             System.err.println(e1.getLocalizedMessage());
276             return;
277         } catch (SMTPException e1) {
278             System.err.println(e1.getMessage());
279             return;
280         }
281         
282         System.exit(0);
283     }
284 }
285
Popular Tags