source: trunk/src/org/expeditee/agents/mail/MailSession.java@ 242

Last change on this file since 242 was 242, checked in by ra33, 16 years ago
File size: 9.9 KB
Line 
1package org.expeditee.agents.mail;
2
3import java.io.BufferedReader;
4import java.io.InputStream;
5import java.io.InputStreamReader;
6import java.util.Date;
7import java.util.Properties;
8
9import javax.mail.Authenticator;
10import javax.mail.Folder;
11import javax.mail.Message;
12import javax.mail.MessagingException;
13import javax.mail.Multipart;
14import javax.mail.Part;
15import javax.mail.PasswordAuthentication;
16import javax.mail.Session;
17import javax.mail.Store;
18import javax.mail.Transport;
19import javax.mail.Flags.Flag;
20import javax.mail.internet.InternetAddress;
21import javax.mail.internet.MimeMessage;
22
23import org.expeditee.gui.AttributeValuePair;
24import org.expeditee.gui.Frame;
25import org.expeditee.gui.MessageBay;
26import org.expeditee.items.Text;
27
28public class MailSession {
29 public static boolean _autoConnect = true;
30
31 private static MailSession _theMailSession = null;
32
33 private Session _session;
34
35 private Transport _transport;
36
37 private Store _store;
38
39 private Folder _folder;
40
41 private String _address;
42
43 private String _username;
44
45 private String _password;
46
47 private String _popServer;
48
49 private Boolean _bConnecting;
50
51 private MailSession(Frame settingsFrame) {
52 _bConnecting = false;
53
54 Properties props = System.getProperties();
55
56 _username = null;
57 _password = "";
58 _popServer = null;
59
60 // Set the settings
61 for (Text item : settingsFrame.getBodyTextItems(false)) {
62 AttributeValuePair avp = new AttributeValuePair(item.getText());
63 if (!avp.hasPair())
64 continue;
65 String attributeFullCase = avp.getAttribute();
66 String attribute = attributeFullCase.toLowerCase();
67
68 if (attribute.equals("user")) {
69 _username = avp.getValue();
70 props.setProperty("mail.user", _username);
71 } else if (attribute.equals("password")) {
72 _password = avp.getValue();
73 props.setProperty("mail.password", _password);
74 } else if (attribute.equals("address")) {
75 _address = avp.getValue();
76 } else if (attribute.equals("smtpserver")) {
77 props.setProperty("mail.transport.protocol", "smtp");
78 props.setProperty("mail.host", avp.getValue());
79 props.setProperty("mail.smtp.starttls.enable", "true");
80 props.setProperty("mail.smtp.host", avp.getValue());
81 props.setProperty("mail.smtp.auth", "true");
82 } else if (attribute.equals("popserver")) {
83 _popServer = avp.getValue();
84 }
85 }
86
87 // Create the authenticator
88 Authenticator auth = null;
89 if (_username != null) {
90 auth = new SMTPAuthenticator(_username, _password);
91 }
92 java.security.Security
93 .addProvider(new com.sun.net.ssl.internal.ssl.Provider());
94
95 // -- Attaching to default Session, or we could start a new one --
96 _session = Session.getDefaultInstance(props, auth);
97 try {
98 // Set up the mail receiver
99 _store = _session.getStore("pop3s");
100
101 // Connect the mail sender
102 _transport = _session.getTransport();
103 if (_autoConnect) {
104 connectThreaded();
105 }
106 } catch (Exception e) {
107 MessageBay.errorMessage("Error in ExpMail setup");
108 }
109 }
110
111 /**
112 * Attempts to connect the mail transporter to the mail server.
113 *
114 */
115 public static void connect() {
116 if (_theMailSession._bConnecting) {
117 MessageBay.errorMessage("Already connecting to mail server");
118 return;
119 } else if (_theMailSession != null) {
120 _theMailSession.connectThreaded();
121 }
122 }
123
124 private void connectThreaded() {
125 Thread t = new ConnectThread(this);
126 t.start();
127 }
128
129 public synchronized void connectServers() {
130 try {
131 if (!_transport.isConnected()) {
132 MessageBay.displayMessage("Connecting to SMTP server...");
133 _bConnecting = true;
134 _transport.connect();
135 MessageBay.overwriteMessage("SMTP server connected");
136 } else {
137 MessageBay.warningMessage("SMTP server already connected");
138 }
139 } catch (MessagingException e) {
140 MessageBay.errorMessage("Error connecting to SMTP server");
141 }
142
143 if (_popServer != null && !_store.isConnected()) {
144 try {
145 MessageBay.displayMessage("Connecting to POP3 server...");
146 _store.connect(_popServer, _username, _password);
147
148 // -- Try to get hold of the default folder --
149 _folder = _store.getDefaultFolder();
150 if (_folder == null)
151 throw new Exception("No default folder");
152 // -- ...and its INBOX --
153 _folder = _folder.getFolder("INBOX");
154 if (_folder == null)
155 throw new Exception("No POP3 INBOX");
156 // -- Open the folder for read only --
157 _folder.open(Folder.READ_ONLY);
158 MessageBay.overwriteMessage("POP3 server connected");
159 MessageBay.warningMessage(getUnreadMessageCount() + " unread messages are in your inbox");
160 } catch (Exception e) {
161 // e.printStackTrace();
162 MessageBay.errorMessage("Error connecting to POP3 server");
163 }
164 }
165 _bConnecting = false;
166 }
167
168 public static boolean sendTextMessage(String to, String cc, String bcc,
169 String subject, String body) {
170
171 if (_theMailSession == null) {
172 MessageBay.errorMessage("Add mail settings to profile frame");
173 return false;
174 }
175
176 if (_theMailSession._bConnecting) {
177 MessageBay.errorMessage("Busy connecting to mail server...");
178 return false;
179 }
180
181 return _theMailSession.sendText(to, cc, bcc, subject, body);
182 }
183
184 private synchronized boolean sendText(String to, String cc, String bcc,
185 String subject, String body) {
186 if (!_transport.isConnected()) {
187 MessageBay
188 .warningMessage("Not connected to server, attempting to reconnect...");
189 try {
190 _bConnecting = true;
191 _transport.connect();
192 _bConnecting = false;
193 } catch (Exception e) {
194 MessageBay.errorMessage("Could not connect to mail server");
195 _bConnecting = false;
196 return false;
197 }
198 }
199
200 if (to == null) {
201 MessageBay.errorMessage("Add tag @to:<sendToEmailAddress>");
202 return false;
203 }
204
205 try {
206 // -- Create a new message --
207 Message msg = new MimeMessage(_session);
208
209 // -- Set the FROM and TO fields --
210 msg.setFrom(new InternetAddress(_address));
211 msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(
212 to, false));
213
214 // -- We could include CC recipients too --
215 if (cc != null) {
216 msg.setRecipients(Message.RecipientType.CC, InternetAddress
217 .parse(cc, false));
218 }
219
220 if (bcc != null) {
221 msg.setRecipients(Message.RecipientType.BCC, InternetAddress
222 .parse(bcc, false));
223 }
224
225 // -- Set the subject and body text --
226 msg.setSubject(subject);
227 msg.setContent(body.toString(), "text/plain");
228
229 // -- Set some other header information --
230 msg.setHeader("ExpMail", "Expeditee");
231 msg.setSentDate(new Date());
232
233 Transport.send(msg, msg.getRecipients(Message.RecipientType.TO));
234 } catch (Exception e) {
235 MessageBay.errorMessage("Error sending mail: " + e.getMessage());
236 return false;
237 }
238 MessageBay.displayMessage("Message sent OK.");
239 return true;
240 }
241
242 public static void init(Frame settingsFrame) {
243
244 if (settingsFrame == null)
245 return;
246
247 if (_theMailSession == null)
248 _theMailSession = new MailSession(settingsFrame);
249 }
250
251 private class SMTPAuthenticator extends javax.mail.Authenticator {
252 private String _username;
253
254 private String _password;
255
256 public SMTPAuthenticator(String username, String password) {
257 _username = username;
258 _password = password;
259 }
260
261 @Override
262 public PasswordAuthentication getPasswordAuthentication() {
263 return new PasswordAuthentication(_username, _password);
264 }
265 }
266
267 public static MailSession getInstance() {
268 return _theMailSession;
269 }
270
271 public synchronized void finalise() {
272 try {
273 if (_transport != null && _transport.isConnected()) {
274 _transport.close();
275 }
276
277 if (_folder != null) {
278 _folder.close(false);
279 }
280
281 if (_store != null) {
282 _store.close();
283 }
284 } catch (Exception e) {
285
286 }
287 }
288
289 public int getUnreadMessageCount() {
290 // -- Get the message wrappers and process them --
291 Message[] msgs;
292 int count = 0;
293 try {
294 msgs = _folder.getMessages();
295 for (int msgNum = 0; msgNum < msgs.length; msgNum++) {
296 if (msgs[msgNum].getFlags().contains(Flag.SEEN))
297 continue;
298 count++;
299 }
300 } catch (MessagingException e) {
301 // TODO Auto-generated catch block
302 e.printStackTrace();
303 }
304 return count;
305 }
306
307 public String getMail() {
308 StringBuffer sb = new StringBuffer();
309 // -- Get the message wrappers and process them --
310 Message[] msgs;
311 try {
312 msgs = _folder.getMessages();
313 for (int msgNum = 0; msgNum < msgs.length; msgNum++) {
314 if (msgs[msgNum].getFlags().contains(Flag.SEEN))
315 continue;
316 // Only get messages that have not been read
317 sb.append(getTextMessage(msgs[msgNum]));
318 sb.append('\n');
319 }
320 } catch (MessagingException e) {
321 e.printStackTrace();
322 }
323 sb.deleteCharAt(sb.length() - 1);
324 return sb.toString();
325 }
326
327 /**
328 * "getTextMessage()" method to print a message.
329 */
330 public String getTextMessage(Message message) {
331 StringBuffer sb = new StringBuffer();
332
333 try {
334 // Get the header information
335 String from = ((InternetAddress) message.getFrom()[0])
336 .getPersonal();
337 if (from == null)
338 from = ((InternetAddress) message.getFrom()[0]).getAddress();
339 sb.append("FROM: " + from);
340 String subject = message.getSubject();
341 sb.append("SUBJECT: " + subject);
342 // -- Get the message part (i.e. the message itself) --
343 Part messagePart = message;
344 Object content = messagePart.getContent();
345 // -- or its first body part if it is a multipart message --
346 if (content instanceof Multipart) {
347 messagePart = ((Multipart) content).getBodyPart(0);
348 System.out.println("[ Multipart Message ]");
349 }
350 // -- Get the content type --
351 String contentType = messagePart.getContentType();
352 // -- If the content is plain text, we can print it --
353 //System.out.println("CONTENT:" + contentType);
354 if (contentType.startsWith("text/plain")
355 || contentType.startsWith("text/html")) {
356 InputStream is = messagePart.getInputStream();
357 BufferedReader reader = new BufferedReader(
358 new InputStreamReader(is));
359 String thisLine = reader.readLine();
360 while (thisLine != null) {
361 sb.append(thisLine);
362 thisLine = reader.readLine();
363 }
364 }
365 sb.append("-----------------------------");
366 } catch (Exception ex) {
367 ex.printStackTrace();
368 }
369 return sb.toString();
370 }
371}
Note: See TracBrowser for help on using the repository browser.