-
Notifications
You must be signed in to change notification settings - Fork 1
/
Email.java
88 lines (70 loc) · 1.87 KB
/
Email.java
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
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
public class Email {
private static Session session;
private static Store store;
private static Folder folder;
// hardcoding protocol and the folder
// it can be parameterized and enhanced as required
private static String protocol = "imaps";
private static String file = "INBOX";
public Email() {
}
public boolean isLoggedIn() {
return store.isConnected();
}
/**
* to login to the mail host server
*/
public static void login(String host, String username, String password) throws Exception {
URLName url = new URLName(protocol, host, 993, file, username, password);
if (session == null) {
Properties props = null;
try {
props = System.getProperties();
} catch (SecurityException sex) {
props = new Properties();
}
session = Session.getInstance(props, null);
}
store = session.getStore(url);
store.connect();
folder = store.getFolder(url);
folder.open(Folder.READ_WRITE);
}
/**
* to logout from the mail host server
*/
public static void logout() throws MessagingException {
folder.close(false);
store.close();
store = null;
session = null;
}
public static int getMessageCount() {
int messageCount = 0;
try {
messageCount = folder.getMessageCount();
} catch (MessagingException me) {
me.printStackTrace();
}
return messageCount;
}
public static Message[] getMessages() throws MessagingException {
return folder.getMessages();
}
public static void main(String[] args) throws Exception {
login("imap.gmail.com", "email", "password");
System.out.println(getMessageCount());
Message[] message = getMessages();
for(Message m: message) {
System.out.println(m.getSubject());
}
logout();
}
}