-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathPOP3SessionJavaMail.java
More file actions
357 lines (310 loc) · 12.9 KB
/
POP3SessionJavaMail.java
File metadata and controls
357 lines (310 loc) · 12.9 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
package com.genexus.internet;
import java.io.*;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Properties;
import java.nio.file.Paths;
import java.util.regex.Pattern;
import com.genexus.diagnostics.core.ILogger;
import com.genexus.diagnostics.core.LogManager;
import jakarta.mail.Flags;
import jakarta.mail.Folder;
import jakarta.mail.Header;
import jakarta.mail.Message;
import jakarta.mail.MessagingException;
import jakarta.mail.Multipart;
import jakarta.mail.NoSuchProviderException;
import jakarta.mail.Part;
import jakarta.mail.Session;
import jakarta.mail.internet.AddressException;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.internet.MimeUtility;
import com.genexus.common.interfaces.SpecificImplementation;
import org.eclipse.angus.mail.pop3.POP3Folder;
import org.eclipse.angus.mail.pop3.POP3Store;
public class POP3SessionJavaMail implements GXInternetConstants, IPOP3Session {
public static final ILogger logger = LogManager.getLogger(POP3SessionJavaMail.class);
private String user;
private String password;
private String attachmentsPath = "";
protected String pop3Host = "192.168.0.1";
protected int pop3Port = 110;
private boolean deleteOnRead;
private boolean readSinceLast;
private boolean secureConnection;
private int timeout;
private int numOfMessages;
private int lastReadMessage;
private StringCollection attachs;
private Session session;
private POP3Store emailStore;
private Boolean downloadAttachments = false;
Message[] messages;
POP3Folder emailFolder;
public POP3SessionJavaMail() {}
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;
timeout = timeout * 1000;
Properties props = new Properties();
props.setProperty("mail.pop3.host", pop3Host);
props.setProperty("mail.pop3.port", String.valueOf(pop3Port));
props.setProperty("mail.pop3.connectiontimeout", String.valueOf(timeout));
props.setProperty("mail.pop3.timeout", String.valueOf(timeout));
String authMethod = sessionInfo.getAuthenticationMethod();
if (!authMethod.isEmpty()) {
props.setProperty("mail.pop3.auth.mechanisms", authMethod.toUpperCase());
if (authMethod.equalsIgnoreCase("XOAUTH2") && pop3Host.equalsIgnoreCase("outlook.office365.com")) {
props.setProperty("mail.pop3.auth.xoauth2.two.line.authentication.format", "true");
}
}
props.setProperty("mail.pop3.ssl.enable", String.valueOf(secureConnection));
session = Session.getInstance(props);
if (logger.isDebugEnabled()) {
session.setDebug(true);
}
try {
emailStore = (POP3Store) session.getStore("pop3");
emailStore.connect(user, password);
emailFolder = (POP3Folder) emailStore.getFolder("INBOX");
emailFolder.open(Folder.READ_WRITE);
lastReadMessage = 0;
if (readSinceLast) {
numOfMessages = emailFolder.getNewMessageCount();
} else {
numOfMessages = emailFolder.getMessageCount();
}
messages = emailFolder.getMessages();
} catch (NoSuchProviderException e) {
log(e.getMessage());
sessionInfo.exceptionHandler(new GXMailException("Can't connect to mail server", MAIL_CantLogin));
} catch (MessagingException me) {
log(me.getMessage());
sessionInfo.exceptionHandler(new GXMailException("Can't connect to mail server", MAIL_CantLogin));
}
}
public void logout(GXPOP3Session sessionInfo) {
try {
emailFolder.close(true);
emailStore.close();
} catch (MessagingException e) {
log(e.getMessage());
sessionInfo.exceptionHandler(new GXMailException(e.getMessage(), MAIL_ConnectionLost));
}
}
public void delete(GXPOP3Session sessionInfo) {
try {
messages[lastReadMessage - 1].setFlag(Flags.Flag.DELETED, true);
} catch (MessagingException e) {
log(e.getMessage());
sessionInfo.exceptionHandler(new GXMailException(e.getMessage(), MAIL_ServerRepliedErr));
}
}
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) {
try {
gxmessage.clear();
setAttachmentsPath(sessionInfo.getAttachDir());
if (lastReadMessage + 1 > numOfMessages)
throw new GXMailException("No messages to receive", MAIL_NoMessages);
Message message = messages[lastReadMessage++];
gxmessage.setFrom(getMailRecipient((InternetAddress) message.getFrom()[0]));
gxmessage.setTo(processRecipients(message, Message.RecipientType.TO));
gxmessage.setCc(processRecipients(message, Message.RecipientType.CC));
gxmessage.setBcc(processRecipients(message, Message.RecipientType.BCC));
MailRecipientCollection mailRecipient = new MailRecipientCollection();
for (int i = 0; i < message.getReplyTo().length; i++) {
InternetAddress addr = ((InternetAddress) message.getReplyTo()[i]);
mailRecipient.addNew(addr.getPersonal(), addr.getAddress());
}
gxmessage.setReplyto(mailRecipient);
gxmessage.setDateSent(message.getSentDate());
gxmessage.setDateReceived(message.getReceivedDate() == null ? com.genexus.CommonUtil.now() : message.getReceivedDate());
gxmessage.setSubject(message.getSubject());
Hashtable headers = new Hashtable();
for (Enumeration en = message.getAllHeaders(); en.hasMoreElements();) {
Header h = (Header) en.nextElement();
headers.put(h.getName(), h.getValue());
}
gxmessage.setHeaders(headers);
attachs = new StringCollection();
Object content = message.getContent();
if (content instanceof Multipart) {
handleMultipart((Multipart) content, gxmessage);
} else {
handlePart(message, gxmessage);
}
} catch (GXMailException e) {
sessionInfo.exceptionHandler(e);
} catch (MessagingException e) {
log(e.getMessage());
sessionInfo.exceptionHandler(new GXMailException(e.getMessage(), MAIL_ServerRepliedErr));
} catch (IOException e) {
log(e.getMessage());
sessionInfo.exceptionHandler(new GXMailException(e.getMessage(), MAIL_ServerRepliedErr));
}
}
private MailRecipient getMailRecipient(InternetAddress inetAdd) {
return new MailRecipient(inetAdd.getPersonal(), inetAdd.getAddress());
}
private MailRecipientCollection processRecipients(Message message, Message.RecipientType rType) throws MessagingException {
MailRecipientCollection mailRecipient = new MailRecipientCollection();
try {
if (message.getRecipients(rType) != null) {
for (int i = 0; i < message.getRecipients(rType).length; i++) {
InternetAddress address = (InternetAddress) message.getRecipients(rType)[i];
mailRecipient.addNew(address.getPersonal(), address.getAddress());
}
}
return mailRecipient;
} catch (AddressException e) {
/*
Some email clients like Gmail separate the list of addresses using commas while others like Outlook separate them using
semicolons. This is a hack to consider the case where the list of addresses is separated with semicolons which produces
an exception because the InternetAddress class used by jakarta mail to parse the addresses expects the list to be separated by commas
*/
String[] addresses = message.getHeader(rType.toString());
if (addresses != null && addresses.length > 0) {
for (String address: addresses) {
String[] splitAddresses = address.replace(";", ",").split(",");
for (String splitAddress: splitAddresses) {
try {
InternetAddress ia = new InternetAddress(splitAddress);
mailRecipient.addNew(ia.getPersonal(), ia.getAddress());
} catch (AddressException ae) {
logger.info("Invalid email address" + splitAddress);
}
}
}
}
return mailRecipient;
}
}
private void handleMultipart(Multipart multipart, GXMailMessage gxmessage) throws MessagingException, IOException {
for (int i = 0, n = multipart.getCount(); i < n; i++) {
handlePart(multipart.getBodyPart(i), gxmessage);
}
}
private boolean findContentTypeHeaderStartingWithMessage(Part part) throws MessagingException {
String[] contentTypeHeader = part.getHeader("Content-Type");
int i = 0;
boolean foundOne = false;
while (i < contentTypeHeader.length && !foundOne) {
if (contentTypeHeader[i].toLowerCase().startsWith("message"))
foundOne = true;
else
i++;
}
return foundOne;
}
private void handlePart(Part part, GXMailMessage gxmessage) throws MessagingException, IOException {
String disposition = part.getDisposition();
boolean isXForwardedFor = part.getContent() instanceof MimeMessage && // Para soportar attachments de mails que llegan a la casilla con el header "X-Forwarded-For"
findContentTypeHeaderStartingWithMessage(part);
if (System.getProperties().getProperty("DownloadAllMailsAttachment", null) != null && isXForwardedFor)
handlePart((MimeMessage) part.getContent(), gxmessage);
if (part.isMimeType("text/plain")) {
gxmessage.setText(part.getContent().toString());
}
if (part.isMimeType("text/html")) {
gxmessage.setHtmltext(part.getContent().toString());
}
if (part.isMimeType("multipart/*")) {
handleMultipart((Multipart) part.getContent(), gxmessage);
}
if (disposition == null && part.isMimeType("application/*")) {
disposition = "UNKNOWN";
}
if (this.downloadAttachments && (disposition != null && (disposition.equalsIgnoreCase(Part.ATTACHMENT) || disposition.equalsIgnoreCase(Part.INLINE) || disposition.equalsIgnoreCase("UNKNOWN")))) {
String fileName = "";
if (part.getFileName() != null)
fileName = MimeUtility.decodeText(part.getFileName());
else if (isXForwardedFor && ((MimeMessage) part.getContent()).getFileName() != null)
fileName = MimeUtility.decodeText(((MimeMessage) part.getContent()).getFileName());
else if (!(part.getContent() instanceof MimeMessage) || ((MimeMessage) part.getContent()).getFileName() == null)
fileName = SpecificImplementation.GXutil.getTempFileName("tmp");
String cid = getAttachmentContentId(part);
if (disposition.equalsIgnoreCase(Part.INLINE) && !cid.isEmpty()) {
fileName = String.format("%s_%s", cid, fileName);
String newHTML = gxmessage.getHtmltext().replace(cid, fileName);
gxmessage.setHtmltext(newHTML);
}
try (InputStream is = part.getContent() instanceof MimeMessage ? ((MimeMessage) part.getContent()).getInputStream() : part.getInputStream()) {
saveFile(fileName, is);
}
attachs.add(attachmentsPath + fileName);
gxmessage.setAttachments(attachs);
}
}
private String getAttachmentContentId(Part part) throws MessagingException {
String cid = "";
String[] cids = part.getHeader("Content-ID");
if (cids != null && !cids[0].isEmpty() && cids[0].startsWith("<") && cids[0].endsWith(">")) {
cid = cids[0].substring(1, cids[0].length() - 1);
}
return cid;
}
private static final String FILE_INVALID_CHARS = "[\\\\/:*?\"<>|\n\r]";
private static final Pattern FILE_INVALID_PATTERN = Pattern.compile(FILE_INVALID_CHARS);
private void saveFile(String filename, InputStream input) throws IOException {
filename = FILE_INVALID_PATTERN.matcher(filename).replaceAll("_");
File file = new File(Paths.get(attachmentsPath, filename).toString());
try (FileOutputStream fos = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(fos); BufferedInputStream bis = new BufferedInputStream(input)) {
int aByte;
while ((aByte = bis.read()) != -1) {
bos.write(aByte);
}
bos.flush();
} catch (IOException e) {
throw new IOException("Error while writing the file", e);
}
}
public String getNextUID() throws GXMailException {
try {
if (lastReadMessage == numOfMessages)
throw new GXMailException("No messages to receive", MAIL_NoMessages);
int messageNum = lastReadMessage + 1;
return emailFolder.getUID(emailFolder.getMessage(messageNum));
} catch (MessagingException e) {
log(e.getMessage());
throw new GXMailException(e.getMessage(), MAIL_ServerRepliedErr);
}
}
public int getMessageCount() throws GXMailException {
try {
if (emailFolder == null || !emailFolder.isOpen())
throw new GXMailException("The email folder is either null or closed", MAIL_ServerRepliedErr);
if (readSinceLast)
return emailFolder.getNewMessageCount();
return emailFolder.getMessageCount();
} catch (MessagingException e) {
log(e.getMessage());
throw new GXMailException(e.getMessage(), MAIL_ServerRepliedErr);
}
}
public void setAttachmentsPath(String _attachmentsPath) {
attachmentsPath = _attachmentsPath.trim();
if (!attachmentsPath.equals("")) {
this.downloadAttachments = true;
}
if (!attachmentsPath.equals("") && !attachmentsPath.endsWith(File.separator)) attachmentsPath += File.separator;
}
private void log(String text) {
logger.debug(text);
}
}