-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMailReceiver.java
More file actions
78 lines (57 loc) · 2.01 KB
/
Copy pathMailReceiver.java
File metadata and controls
78 lines (57 loc) · 2.01 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
package Assignment1.EmailClient;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Properties;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.FlagTerm;
public class MailReceiver implements Runnable {
private MyBlockingQueue queue;
private static final String email_id = "ylclient19@gmail.com";
private static final String password = "Client@123";
private Properties properties;
private final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss");
private Observable[] observers;
public MailReceiver(MyBlockingQueue queue, Observable[] observers) {
this.queue = queue;
this.observers = observers;
properties = new Properties();
properties.put("mail.store.protocol", "imaps");
properties.put("mail.imaps.host", "imap.gmail.com");
properties.put("mail.imaps.port", "993");
}
@Override
public void run() {
while (true) {
try {
Session session = Session.getDefaultInstance(properties, null);
Store store = session.getStore("imaps");
store.connect(email_id, password);
Folder inbox = store.getFolder("inbox");
inbox.open(Folder.READ_WRITE);
if (inbox.getUnreadMessageCount() > 0) {
for (Observable observer : observers) {
observer.notify(dtf.format(LocalDateTime.now()));
}
javax.mail.Message[] messages = inbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
for (javax.mail.Message message : messages) {
Email mail = null;
try {
mail = new Email(message.getFrom()[0].toString(), "ylclient19@gmail.com",
message.getSubject(), message.getContent().toString());
} catch (IOException e) {
// TODO Auto-generated catch block
}
queue.addToQueue(mail);
message.setFlags(new Flags(Flags.Flag.SEEN), true);
}
}
} catch (MessagingException e) {
}
}
}
}