KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > armedbear > j > mail > Mail


1 /*
2  * Mail.java
3  *
4  * Copyright (C) 2000-2003 Peter Graves
5  * $Id: Mail.java,v 1.2 2003/06/29 00:19:34 piso Exp $
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20  */

21
22 package org.armedbear.j.mail;
23
24 import java.io.UnsupportedEncodingException JavaDoc;
25 import java.io.Writer JavaDoc;
26 import java.net.InetAddress JavaDoc;
27 import java.text.SimpleDateFormat JavaDoc;
28 import java.util.Calendar JavaDoc;
29 import java.util.List JavaDoc;
30 import org.armedbear.j.Directories;
31 import org.armedbear.j.Editor;
32 import org.armedbear.j.File;
33 import org.armedbear.j.FastStringBuffer;
34 import org.armedbear.j.FastStringReader;
35 import org.armedbear.j.Headers;
36 import org.armedbear.j.Log;
37 import org.armedbear.j.Property;
38 import org.armedbear.j.Utilities;
39
40 public final class Mail
41 {
42     private static File sentMessagesFile;
43
44     public static final File getSentMessagesFile()
45     {
46         final String JavaDoc fcc = Editor.preferences().getStringProperty(Property.FCC);
47         if (fcc == null)
48             return null;
49
50         // For now, we just support a hard-coded scheme.
51
if (!fcc.equals("sent"))
52             return null;
53
54         if (sentMessagesFile == null) {
55             File local =
56                 File.getInstance(Directories.getMailDirectory(), "local");
57             File sent = File.getInstance(local, "sent");
58             if (!sent.isDirectory())
59                 sent.mkdirs();
60             if (sent.isDirectory())
61                 sentMessagesFile = File.getInstance(sent, "mbox");
62         }
63         return sentMessagesFile;
64     }
65
66     public static final MailAddress getUserMailAddress()
67     {
68         String JavaDoc address = Editor.preferences().getStringProperty(Property.USER_MAIL_ADDRESS);
69         if (address == null)
70             return null;
71         return new MailAddress(Editor.preferences().getStringProperty(Property.USER_FULL_NAME), address);
72     }
73
74     public static boolean bounceMessage(Message message, MailAddress[] to)
75     {
76         if (message == null)
77             return false;
78         if (to == null)
79             return false;
80         SmtpSession session = SmtpSession.getDefaultSession();
81         if (session == null)
82             return false;
83         boolean succeeded = bounceMessage(message, to, session);
84         session.quit();
85         return succeeded;
86     }
87
88     public static boolean bounceMessage(Message message, MailAddress[] to,
89         SmtpSession session)
90     {
91         if (message == null)
92             return false;
93         if (to == null)
94             return false;
95         if (session == null)
96             return false;
97         session.setEcho(true);
98         session.writeLine("rset");
99         int response = session.getResponse();
100         if (response == 500) {
101             // "command unrecognized"
102
Log.warn("bounceMessage calling session.quit()...");
103             session.quit();
104             Log.warn("bounceMessage calling session.reconnect()...");
105             if (!session.connect())
106                 return false;
107             session.writeLine("rset");
108             response = session.getResponse();
109         }
110         if (response != 250)
111             return false;
112         session.writeLine("mail from:<" + getUserMailAddress().getAddress() + ">");
113         if (session.getResponse() != 250)
114             return false;
115         for (int i = 0; i < to.length; i++) {
116             String JavaDoc address = to[i].getAddress();
117             session.writeLine("rcpt to: " + address);
118             if (session.getResponse() != 250)
119                 return false;
120         }
121         session.writeLine("data");
122         if (session.getResponse() != 354)
123             return false;
124         session.setEcho(false);
125         if (!writeMessageText(message, to, session))
126             return false;
127         session.setEcho(true);
128         session.writeLine(".");
129         boolean succeeded = session.getResponse() == 250;
130         session.setEcho(false);
131         return succeeded;
132     }
133
134     private static boolean writeMessageText(Message message, MailAddress[] to,
135         Writer JavaDoc writer)
136     {
137         try {
138             FastStringReader reader =
139                 new FastStringReader(message.getRawHeaders());
140             String JavaDoc s;
141             while((s = reader.readLine()) != null) {
142                 if (s.startsWith("X-J-Status"))
143                     continue;
144                 if (s.startsWith("X-UIDL"))
145                     continue;
146                 writer.write(s);
147                 writer.write("\r\n");
148             }
149
150             // Add "Resent" headers.
151
writer.write("Resent-From: ");
152             writer.write(getUserMailAddress().toString());
153             writer.write("\r\n");
154
155             writer.write("Resent-Date: ");
156             writer.write(RFC822Date.getDateTimeString());
157             writer.write("\r\n");
158
159             writer.write("Resent-To: ");
160             int length = 11;
161             for (int i = 0; i < to.length; i++) {
162                 String JavaDoc address = to[i].toString();
163                 if (length + address.length() > 76) {
164                     writer.write("\r\n\t");
165                     length = 8; // Assuming tab width is 8.
166
}
167                 writer.write(address);
168                 length += address.length();
169                 if (i < to.length-1) {
170                     writer.write(", ");
171                     length += 2;
172                 }
173             }
174             writer.write("\r\n");
175
176             writer.write("Resent-Message-Id: ");
177             writer.write(generateMessageId());
178             writer.write("\r\n");
179
180             // Terminate headers.
181
writer.write("\r\n");
182
183             // Body.
184
String JavaDoc body = message.getRawBody();
185             String JavaDoc contentType = message.getHeaderValue(Headers.CONTENT_TYPE);
186             if (contentType != null) {
187                 String JavaDoc charset =
188                     Utilities.getCharsetFromContentType(contentType);
189                 String JavaDoc encoding = Utilities.getEncodingFromCharset(charset);
190                 if (!encoding.equalsIgnoreCase("iso-8859-1")) {
191                     try {
192                         byte[] bytes = body.getBytes(encoding);
193                         body = new String JavaDoc(bytes, 0);
194                     }
195                     catch (UnsupportedEncodingException JavaDoc e) {
196                         Log.error(e);
197                     }
198                 }
199             }
200             writer.write(body);
201             if (!body.endsWith("\r\n"))
202                 writer.write("\r\n");
203             return true;
204         }
205         catch (Exception JavaDoc e) {
206             Log.error(e);
207             return false;
208         }
209     }
210
211     private static long messageIdentifier = System.currentTimeMillis() % 10000;
212
213     public static String JavaDoc generateMessageId()
214     {
215         String JavaDoc hostName = null;
216         try {
217             InetAddress JavaDoc addr = InetAddress.getLocalHost();
218             hostName = addr.getHostName();
219         }
220         catch (Exception JavaDoc e) {
221             Log.error(e);
222         }
223         if (hostName == null)
224             hostName = "unknown"; // Avoid NPE below.
225
SimpleDateFormat JavaDoc df = new SimpleDateFormat JavaDoc ("yyyyMMddHHmmss");
226         Calendar JavaDoc cal = Calendar.getInstance();
227         FastStringBuffer sb = new FastStringBuffer(128);
228         sb.append('<');
229         sb.append(df.format(cal.getTime()));
230         sb.append('.');
231         sb.append(messageIdentifier++);
232         sb.append('@');
233         sb.append(hostName);
234         sb.append('>');
235         return sb.toString();
236     }
237
238     public static boolean writeFcc(Message message, String JavaDoc destination, int flags)
239     {
240         if (destination.startsWith("mailbox:"))
241             destination = destination.substring(8);
242         File file = File.getInstance(destination);
243         if (file == null)
244             return false;
245         if (!file.isLocal())
246             return false;
247         Mbox mbox = Mbox.getInstance(file);
248         if (!mbox.lock())
249             return false;
250         boolean result = mbox.appendMessage(message, flags);
251         mbox.unlock();
252         mbox.updateViews();
253         return result;
254     }
255 }
256
Popular Tags