-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathPOP3Session.java
More file actions
528 lines (445 loc) · 13.3 KB
/
POP3Session.java
File metadata and controls
528 lines (445 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
package com.genexus.internet;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.TimeZone;
import com.genexus.CommonUtil;
import com.genexus.common.interfaces.SpecificImplementation;
import com.genexus.platform.INativeFunctions;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.protocol.BasicHttpContext;
public class POP3Session implements GXInternetConstants,IPOP3Session
{
private final int CONN_NORMAL = 0;
private final int CONN_TLS = 1;
private final int CONN_SSL = 2;
private boolean DEBUG = GXInternetConstants.DEBUG;
private PrintStream logOutput;
private String user;
private String password;
private String attachmentsPath = "";
protected String pop3Host = "192.168.0.1";
protected int pop3Port = 110;
private boolean displayMessages;
private boolean deleteOnRead;
private boolean readSinceLast;
private boolean secureConnection;
private int lastError;
private int timeout;
private int numOfMessages;
private int lastReadMessage;
protected BufferedReader in = null;
protected PrintWriter out = null;
protected Socket socket = null;
public static final byte[] lineSeparator = System.getProperty("line.separator").getBytes();
public static final String CRLF = "\r\n";
private Boolean downloadAttachments = false;
public POP3Session()
{
if (DEBUG)
{
try
{
logOutput = new PrintStream(new FileOutputStream(new File("_gx_pop3.log")));
}
catch (IOException e)
{
System.out.println("Can't open POP3 log file pop3.log");
}
}
}
public int error()
{
return lastError;
}
public void login(GXPOP3Session sessionInfo)
{
this.pop3Host = sessionInfo.getHost();
this.pop3Port = sessionInfo.getPort();
this.timeout = sessionInfo.getTimeout();
this.user = sessionInfo.getUserName();
this.password = sessionInfo.getPassword();
this.deleteOnRead = false;
this.readSinceLast = sessionInfo.getNewMessages() != 0;
this.secureConnection = sessionInfo.getSecure() != 0;
try
{
connectAndLogin();
}
catch (GXMailException e)
{
sessionInfo.exceptionHandler(e);
}
}
private void connectAndLogin() throws GXMailException
{
if(secureConnection)
{
try
{
connectSSL();
}
catch(GXMailException e1)
{
if (socket != null)
{
closeSafe();
}
connectTLS();
}
}
else
{
connectNormal();
}
}
private void connectSSL() throws GXMailException
{
connect(CONN_SSL);
login();
}
private void connectTLS() throws GXMailException
{
connect(CONN_TLS);
login();
}
private void connectNormal() throws GXMailException
{
connect(CONN_NORMAL);
login();
}
private Socket getConnectionSocket(int type) throws UnknownHostException, IOException
{
InetAddress ipAddr = InetAddress.getByName(pop3Host.trim());
SSLConnectionSocketFactory sslConn;
switch(type)
{
case CONN_NORMAL:
return new Socket(pop3Host.trim(), pop3Port);
case CONN_TLS:
sslConn = SSLConnConstructor.getSSLSecureInstance(new String[] { "TLSv1.1", "TLSv1.2" });
return sslConn.createLayeredSocket(new Socket(pop3Host.trim(), pop3Port),ipAddr.getHostName(),pop3Port,new BasicHttpContext());
case CONN_SSL:
sslConn = SSLConnConstructor.getSSLSecureInstance(new String[] { "TLSv1" });
return sslConn.createLayeredSocket(new Socket(pop3Host.trim(), pop3Port),ipAddr.getHostName(),pop3Port,new BasicHttpContext());
}
return new Socket(pop3Host.trim(), pop3Port);
}
public void logout(GXPOP3Session sessionInfo)
{
try
{
logout();
}
catch (GXMailException e)
{
sessionInfo.exceptionHandler(e);
}
}
public void delete(GXPOP3Session sessionInfo)
{
try
{
dele(lastReadMessage);
}
catch (GXMailException e)
{
sessionInfo.exceptionHandler(e);
}
}
public void skip(GXPOP3Session sessionInfo)
{
try
{
if (lastReadMessage == numOfMessages)
throw new GXMailException("No messages to receive", MAIL_NoMessages);
++lastReadMessage;
}
catch (GXMailException e)
{
sessionInfo.exceptionHandler(e);
}
}
public void receive(GXPOP3Session sessionInfo, GXMailMessage gxmessage)
{
// TODO: Aqui podria pasar que hubiera entrado un nuevo mail desde que empec�
// a leer, y lo mas razonable seria leerlo. Eso implicaria chequear de nuevo
// la cantidad de mensajes que existen, y compararlo con la cantidad de mensajes
// leidos, dependiendo del parametro de si hay que borrar o no los mensajes.
try
{
setAttachmentsPath(sessionInfo.getAttachDir()); // Obtengo el AttachmentsPath
if (lastReadMessage == numOfMessages)
throw new GXMailException("No messages to receive", MAIL_NoMessages);
MailMessage message = retr(++lastReadMessage, attachmentsPath);
QuotedPrintableDecoder dec = new QuotedPrintableDecoder();
gxmessage.setFrom(MailRecipient.getFromString(message.getField(GXInternetConstants.FROM)));
gxmessage.setTo(MailRecipientCollection.getFromString(message.getField(GXInternetConstants.TO).trim()));
gxmessage.setCc(MailRecipientCollection.getFromString(message.getField(GXInternetConstants.CC).trim()));
gxmessage.setReplyto(MailRecipientCollection.getFromString(message.getField(GXInternetConstants.REPLY_TO).trim()));
try {
Date d = new Date(message.getField(GXInternetConstants.DATE));
d = SpecificImplementation.GXutil.DateTimefromTimeZone(d, TimeZone.getDefault().getID(), SpecificImplementation.Application.getModelContext());
gxmessage.setDateSent(d);
} catch (IllegalArgumentException e) {
gxmessage.setDateSent(CommonUtil.nullDate());
}
try {
Date d = new Date(message.getReceivedDate());
d = SpecificImplementation.GXutil.DateTimefromTimeZone(d, TimeZone.getDefault().getID(), SpecificImplementation.Application.getModelContext());
gxmessage.setDateReceived(d);
} catch (IllegalArgumentException e) {
gxmessage.setDateReceived(gxmessage.getDateSent());
}
gxmessage.setSubject(dec.decodeHeader(message.getField(GXInternetConstants.SUBJECT)));
gxmessage.setHeaders(message.getKeys());
gxmessage.setText(message.getText());
gxmessage.setHtmltext(message.getHtmlText());
gxmessage.setAttachments(StringCollection.getFromString(message.getAttachments()));
}
catch (GXMailException e)
{
sessionInfo.exceptionHandler(e);
}
catch (IOException e)
{
setError(e);
sessionInfo.exceptionHandler(new GXMailException(e.getMessage(), MAIL_ConnectionLost));
}
}
public void setDisplayMessages(int displayMessages)
{
}
public void setAttachmentsPath(String _attachmentsPath)
{
attachmentsPath = _attachmentsPath.trim();
if (!attachmentsPath.equals(""))
{
this.downloadAttachments = true;
}
if(!attachmentsPath.equals("") && !attachmentsPath.endsWith(File.separator))attachmentsPath += File.separator;
}
void login() throws GXMailException
{
doCommand( "USER " + user);
doCommand( "PASS " + password);
numOfMessages = getValue("STAT");
try
{
lastReadMessage = readSinceLast?getValue("LAST"):0;
}
catch (GXMailException e)
{
throw new GXMailException("POP3 server does not support NewMessages = 1", MAIL_LastNotSupported);
}
lastError = 0;
}
public String getNextUID() throws GXMailException
{
if (lastReadMessage == numOfMessages)
throw new GXMailException("No messages to receive", MAIL_NoMessages);
int messageNum = lastReadMessage +1;
String reply = doCommand("UIDL " + messageNum);
int pos1 = reply.indexOf(' ');
int pos2 = reply.indexOf(' ', pos1 + 1);
return reply.substring(pos2).trim();
}
public int getMessageCount() throws GXMailException
{
int ret = getValue("STAT");
if (readSinceLast)
return ret - getValue("LAST");
return ret;
}
public boolean isLoggedIn()
{
return socket != null;
}
public void logout() throws GXMailException
{
try
{
doCommand("QUIT");
this.socket.close();
socket = null;
}
catch (IOException e)
{
throw new GXMailException(e.getMessage(), MAIL_ConnectionLost);
}
}
private void closeSafe()
{
try
{
this.socket.close();
socket = null;
}
catch (IOException e)
{
}
}
/**
* Open a TCP socket to the server.
*/
private void connect(final int type) throws GXMailException
{
try
{
SpecificImplementation.NativeFunctions.getInstance().executeWithPermissions(
new Runnable() {
public void run()
{
try
{
socket = getConnectionSocket(type);
}
catch (IOException e)
{
}
}
}, INativeFunctions.CONNECT);
if (socket == null)
throw new GXMailException("Can't connect to mail server", MAIL_CantLogin);
socket.setSoTimeout(timeout * 1000);
socket.setTcpNoDelay(true);
InputStream sin = socket.getInputStream();
in = new BufferedReader(new InputStreamReader(sin));
out = new PrintWriter(socket.getOutputStream());
doCommand(null);
}
catch(SocketException e)
{
throw new GXMailException("Error opening the socket connection. " + e.getMessage(), MAIL_CantLogin);
}
catch(UnknownHostException e)
{
throw new GXMailException("Error while opening socket: Host Unknown: " + pop3Host + " " +e.getMessage(), MAIL_CantLogin);
}
catch(IOException e)
{
throw new GXMailException("Error while trying to read or write. " + e.getMessage(), MAIL_CantLogin);
}
}
private void dele(int i) throws GXMailException
{
doCommand( "DELE " + i);
}
private MailMessage retr(int i, String attachmentPath) throws GXMailException
{
doCommand("RETR " + i);
return new MailMessage(new RFC822Reader(new RFC822EndReader(in, logOutput)), attachmentPath, this.downloadAttachments);
}
private int getValue(String command) throws GXMailException
{
int pos1, pos2, res;
String reply = doCommand(command);
// Get the number of messages - Sample reply="+OK 2 234"
reply = reply.trim();
pos1 = reply.indexOf(' ');
pos2 = reply.indexOf(' ', pos1 + 1);
if (pos2 > 0)
res = Integer.parseInt(reply.substring(pos1, pos2).trim());
else
res = Integer.parseInt(reply.substring(pos1).trim());
return res;
}
private void msg(String msg)
{
System.err.println(msg);
}
private void setError(Exception e)
{
lastError = 1;
if (displayMessages)
msg(e.getMessage());
}
private void log(String text)
{
if (DEBUG)
if (logOutput != null)
logOutput.println(text);
}
protected String doCommand(String commandString) throws GXMailException
{
try
{
if (commandString != null)
{
if (DEBUG)
if (!commandString.startsWith("PASS"))
log("OUT : " + commandString);
else
log("OUT : PASS *****");
out.print(commandString);
out.print(CRLF);
out.flush();
}
String reply = in.readLine();
if (reply == null)
throw new GXMailException("Server reply invalid: ", MAIL_ServerReplyInvalid);
reply = reply.trim();
if((commandString != null) && commandString.startsWith("RETR") && (reply.length() == 0))
{//Esto es porque hay casos en que antes de la respuesta viene una linea, en particular esta
//pasando con gmail.
String otherLine = in.readLine();
if (otherLine != null) { reply = otherLine.trim(); }
}
if (DEBUG)
log("IN : " + reply);
// code change for ver 2.0 wherein there need not
// be any error message along with the error reply
String serverReply = "";
if ((reply.indexOf(' ')) != -1)
serverReply = reply.substring(reply.indexOf(' '));
// end code change
if (reply.startsWith("-ERR"))
{
throw new GXMailException("Server replied with an error: " + serverReply, MAIL_ServerRepliedErr);
}
if (reply.startsWith("+OK"))
return reply;
throw new GXMailException("Server reply invalid: " + reply, MAIL_ServerReplyInvalid);
}
catch (IOException e)
{
throw new GXMailException(e.getMessage(), MAIL_ConnectionLost);
}
}
}
/*
------=_NextPart_000_0003_01BEB695.8E0E8090
Content-Type: application/x-msexcel;
name="XlsRep.xls"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename="XlsRep.xls"
------=_NextPart_000_0003_01BEB695.8E0E8090
Content-Type: image/gif;
name="BannerFILE1.gif"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename="BannerFILE1.gif"
------=_NextPart_000_0003_01BEB695.8E0E8090
Content-Type: application/msword;
name="Web Transactions.doc"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename="Web Transactions.doc"
------=_NextPart_000_0003_01BEB695.8E0E8090
Content-Type: text/html;
name="tst.html"
Content-Transfer-Encoding: quoted-printable
Content-Disposition: attachment;
filename="tst.html"
*/