forked from angiejones/email-test-automation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEmailUtils.java
More file actions
295 lines (237 loc) · 8.89 KB
/
EmailUtils.java
File metadata and controls
295 lines (237 loc) · 8.89 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
package utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.SubjectTerm;
/**
* Utility for interacting with an Email application
*/
public class EmailUtils {
private Folder folder;
public enum EmailFolder {
INBOX("INBOX"),
SPAM("SPAM");
private String text;
private EmailFolder(String text){
this.text = text;
}
public String getText() {
return text;
}
}
/**
* Uses email.username and email.password properties from the properties file. Reads from Inbox folder of the email application
* @throws MessagingException
*/
public EmailUtils() throws MessagingException {
this(EmailFolder.INBOX);
}
/**
* Uses username and password in properties file to read from a given folder of the email application
* @param emailFolder Folder in email application to interact with
* @throws MessagingException
*/
public EmailUtils(EmailFolder emailFolder) throws MessagingException {
this(getEmailUsernameFromProperties(),
getEmailPasswordFromProperties(),
getEmailServerFromProperties(),
emailFolder);
}
/**
* Connects to email server with credentials provided to read from a given folder of the email application
* @param username Email username (e.g. janedoe@email.com)
* @param password Email password
* @param server Email server (e.g. smtp.email.com)
* @param emailFolder Folder in email application to interact with
*/
public EmailUtils(String username, String password, String server, EmailFolder emailFolder) throws MessagingException {
Properties props = System.getProperties();
try {
props.load(new FileInputStream(new File("resources/email.properties")));
} catch(Exception e) {
e.printStackTrace();
System.exit(-1);
}
Session session = Session.getInstance(props);
Store store = session.getStore("imaps");
store.connect(server, username, password);
folder = store.getFolder(emailFolder.getText());
folder.open(Folder.READ_WRITE);
}
//************* GET EMAIL PROPERTIES *******************
public static String getEmailAddressFromProperties(){
return System.getProperty("email.address");
}
public static String getEmailUsernameFromProperties(){
return System.getProperty("email.username");
}
public static String getEmailPasswordFromProperties(){
return System.getProperty("email.password");
}
public static String getEmailProtocolFromProperties(){
return System.getProperty("email.protocol");
}
public static int getEmailPortFromProperties(){
return Integer.parseInt(System.getProperty("email.port"));
}
public static String getEmailServerFromProperties(){
return System.getProperty("email.server");
}
//************* EMAIL ACTIONS *******************
public void openEmail(Message message) throws Exception{
message.getContent();
}
public int getNumberOfMessages() throws MessagingException {
return folder.getMessageCount();
}
public int getNumberOfUnreadMessages()throws MessagingException {
return folder.getUnreadMessageCount();
}
/**
* Gets a message by its position in the folder. The earliest message is indexed at 1.
*/
public Message getMessageByIndex(int index) throws MessagingException {
return folder.getMessage(index);
}
public Message getLatestMessage() throws MessagingException{
return getMessageByIndex(getNumberOfMessages());
}
/**
* Gets all messages within the folder
*/
public Message[] getAllMessages() throws MessagingException {
return folder.getMessages();
}
/**
* @param maxToGet maximum number of messages to get, starting from the latest. For example, enter 100 to get the last 100 messages received.
*/
public Message[] getMessages(int maxToGet) throws MessagingException {
Map<String, Integer> indices = getStartAndEndIndices(maxToGet);
return folder.getMessages(indices.get("startIndex"), indices.get("endIndex"));
}
/**
* Searches for messages with a specific subject
* @param subject Subject to search messages for
* @param unreadOnly Indicate whether to only return matched messages that are unread
* @param maxToSearch maximum number of messages to search, starting from the latest. For example, enter 100 to search through the last 100 messages.
*/
public Message[] getMessagesBySubject(String subject, boolean unreadOnly, int maxToSearch) throws Exception{
Map<String, Integer> indices = getStartAndEndIndices(maxToSearch);
Message messages[] = folder.search(
new SubjectTerm(subject),
folder.getMessages(indices.get("startIndex"), indices.get("endIndex")));
if(unreadOnly){
List<Message> unreadMessages = new ArrayList<Message>();
for (Message message : messages) {
if(isMessageUnread(message)) {
unreadMessages.add(message);
}
}
messages = unreadMessages.toArray(new Message[]{});
}
return messages;
}
/**
* Returns HTML of the email's content
*/
public String getMessageContent(Message message) throws Exception {
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(message.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
}
/**
* Returns all urls from an email message with the linkText specified
*/
public List<String> getUrlsFromMessage(Message message, String linkText) throws Exception{
String html = getMessageContent(message);
List<String> allMatches = new ArrayList<String>();
Matcher matcher = Pattern.compile("(<a [^>]+>)"+linkText+"</a>").matcher(html);
while (matcher.find()) {
String aTag = matcher.group(1);
allMatches.add(aTag.substring(aTag.indexOf("http"), aTag.indexOf("\">")));
}
return allMatches;
}
private Map<String, Integer> getStartAndEndIndices(int max) throws MessagingException {
int endIndex = getNumberOfMessages();
int startIndex = endIndex - max;
//In event that maxToGet is greater than number of messages that exist
if(startIndex < 1){
startIndex = 1;
}
Map<String, Integer> indices = new HashMap<String, Integer>();
indices.put("startIndex", startIndex);
indices.put("endIndex", endIndex);
return indices;
}
/**
* Gets text from the end of a line.
* In this example, the subject of the email is 'Authorization Code'
* And the line to get the text from begins with 'Authorization code:'
* Change these items to whatever you need for your email. This is only an example.
*/
public String getAuthorizationCode() throws Exception {
Message email = getMessagesBySubject("Authorization Code", true, 5)[0];
BufferedReader reader = new BufferedReader(new InputStreamReader(email.getInputStream()));
String line;
String prefix = "Authorization code:";
while ((line = reader.readLine()) != null) {
if(line.startsWith(prefix)) {
return line.substring(line.indexOf(":") + 1);
}
}
return null;
}
/**
* Gets one line of text
* In this example, the subject of the email is 'Authorization Code'
* And the line preceding the code begins with 'Authorization code:'
* Change these items to whatever you need for your email. This is only an example.
*/
public String getVerificationCode() throws Exception {
Message email = getMessagesBySubject("Authorization Code", true, 5)[0];
BufferedReader reader = new BufferedReader(new InputStreamReader(email.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
if(line.startsWith("Authorization code:")) {
return reader.readLine();
}
}
return null;
}
//************* BOOLEAN METHODS *******************
/**
* Searches an email message for a specific string
*/
public boolean isTextInMessage(Message message, String text) throws Exception {
String content = getMessageContent(message);
//Some Strings within the email have whitespace and some have break coding. Need to be the same.
content = content.replace(" ", " ");
return content.contains(text);
}
public boolean isMessageInFolder(String subject, boolean unreadOnly) throws Exception {
int messagesFound = getMessagesBySubject(subject, unreadOnly, getNumberOfMessages()).length;
return messagesFound > 0;
}
public boolean isMessageUnread(Message message) throws Exception {
return !message.isSet(Flags.Flag.SEEN);
}
}