├── EmailUtils.java └── README.md /EmailUtils.java: -------------------------------------------------------------------------------- 1 | package utils; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.File; 5 | import java.io.FileInputStream; 6 | import java.io.InputStreamReader; 7 | import java.util.ArrayList; 8 | import java.util.HashMap; 9 | import java.util.List; 10 | import java.util.Map; 11 | import java.util.Properties; 12 | import java.util.regex.Matcher; 13 | import java.util.regex.Pattern; 14 | 15 | import javax.mail.Flags; 16 | import javax.mail.Folder; 17 | import javax.mail.Message; 18 | import javax.mail.MessagingException; 19 | import javax.mail.Session; 20 | import javax.mail.Store; 21 | import javax.mail.search.SubjectTerm; 22 | 23 | 24 | 25 | /** 26 | * Utility for interacting with an Email application 27 | */ 28 | public class EmailUtils { 29 | 30 | private Folder folder; 31 | 32 | public enum EmailFolder { 33 | INBOX("INBOX"), 34 | SPAM("SPAM"); 35 | 36 | private String text; 37 | 38 | private EmailFolder(String text){ 39 | this.text = text; 40 | } 41 | 42 | public String getText() { 43 | return text; 44 | } 45 | } 46 | 47 | /** 48 | * Uses email.username and email.password properties from the properties file. Reads from Inbox folder of the email application 49 | * @throws MessagingException 50 | */ 51 | public EmailUtils() throws MessagingException { 52 | this(EmailFolder.INBOX); 53 | } 54 | 55 | /** 56 | * Uses username and password in properties file to read from a given folder of the email application 57 | * @param emailFolder Folder in email application to interact with 58 | * @throws MessagingException 59 | */ 60 | public EmailUtils(EmailFolder emailFolder) throws MessagingException { 61 | this(getEmailUsernameFromProperties(), 62 | getEmailPasswordFromProperties(), 63 | getEmailServerFromProperties(), 64 | emailFolder); 65 | } 66 | 67 | /** 68 | * Connects to email server with credentials provided to read from a given folder of the email application 69 | * @param username Email username (e.g. janedoe@email.com) 70 | * @param password Email password 71 | * @param server Email server (e.g. smtp.email.com) 72 | * @param emailFolder Folder in email application to interact with 73 | */ 74 | public EmailUtils(String username, String password, String server, EmailFolder emailFolder) throws MessagingException { 75 | Properties props = System.getProperties(); 76 | try { 77 | props.load(new FileInputStream(new File("resources/email.properties"))); 78 | } catch(Exception e) { 79 | e.printStackTrace(); 80 | System.exit(-1); 81 | } 82 | 83 | Session session = Session.getInstance(props); 84 | Store store = session.getStore("imaps"); 85 | store.connect(server, username, password); 86 | 87 | 88 | folder = store.getFolder(emailFolder.getText()); 89 | folder.open(Folder.READ_WRITE); 90 | } 91 | 92 | 93 | 94 | //************* GET EMAIL PROPERTIES ******************* 95 | 96 | public static String getEmailAddressFromProperties(){ 97 | return System.getProperty("email.address"); 98 | } 99 | 100 | public static String getEmailUsernameFromProperties(){ 101 | return System.getProperty("email.username"); 102 | } 103 | 104 | public static String getEmailPasswordFromProperties(){ 105 | return System.getProperty("email.password"); 106 | } 107 | 108 | public static String getEmailProtocolFromProperties(){ 109 | return System.getProperty("email.protocol"); 110 | } 111 | 112 | public static int getEmailPortFromProperties(){ 113 | return Integer.parseInt(System.getProperty("email.port")); 114 | } 115 | 116 | public static String getEmailServerFromProperties(){ 117 | return System.getProperty("email.server"); 118 | } 119 | 120 | 121 | 122 | 123 | //************* EMAIL ACTIONS ******************* 124 | 125 | public void openEmail(Message message) throws Exception{ 126 | message.getContent(); 127 | } 128 | 129 | public int getNumberOfMessages() throws MessagingException { 130 | return folder.getMessageCount(); 131 | } 132 | 133 | public int getNumberOfUnreadMessages()throws MessagingException { 134 | return folder.getUnreadMessageCount(); 135 | } 136 | 137 | /** 138 | * Gets a message by its position in the folder. The earliest message is indexed at 1. 139 | */ 140 | public Message getMessageByIndex(int index) throws MessagingException { 141 | return folder.getMessage(index); 142 | } 143 | 144 | public Message getLatestMessage() throws MessagingException{ 145 | return getMessageByIndex(getNumberOfMessages()); 146 | } 147 | 148 | /** 149 | * Gets all messages within the folder 150 | */ 151 | public Message[] getAllMessages() throws MessagingException { 152 | return folder.getMessages(); 153 | } 154 | 155 | /** 156 | * @param maxToGet maximum number of messages to get, starting from the latest. For example, enter 100 to get the last 100 messages received. 157 | */ 158 | public Message[] getMessages(int maxToGet) throws MessagingException { 159 | Map indices = getStartAndEndIndices(maxToGet); 160 | return folder.getMessages(indices.get("startIndex"), indices.get("endIndex")); 161 | } 162 | 163 | /** 164 | * Searches for messages with a specific subject 165 | * @param subject Subject to search messages for 166 | * @param unreadOnly Indicate whether to only return matched messages that are unread 167 | * @param maxToSearch maximum number of messages to search, starting from the latest. For example, enter 100 to search through the last 100 messages. 168 | */ 169 | public Message[] getMessagesBySubject(String subject, boolean unreadOnly, int maxToSearch) throws Exception{ 170 | Map indices = getStartAndEndIndices(maxToSearch); 171 | 172 | Message messages[] = folder.search( 173 | new SubjectTerm(subject), 174 | folder.getMessages(indices.get("startIndex"), indices.get("endIndex"))); 175 | 176 | if(unreadOnly){ 177 | List unreadMessages = new ArrayList(); 178 | for (Message message : messages) { 179 | if(isMessageUnread(message)) { 180 | unreadMessages.add(message); 181 | } 182 | } 183 | messages = unreadMessages.toArray(new Message[]{}); 184 | } 185 | 186 | return messages; 187 | } 188 | 189 | /** 190 | * Returns HTML of the email's content 191 | */ 192 | public String getMessageContent(Message message) throws Exception { 193 | StringBuilder builder = new StringBuilder(); 194 | BufferedReader reader = new BufferedReader(new InputStreamReader(message.getInputStream())); 195 | String line; 196 | while ((line = reader.readLine()) != null) { 197 | builder.append(line); 198 | } 199 | return builder.toString(); 200 | } 201 | 202 | /** 203 | * Returns all urls from an email message with the linkText specified 204 | */ 205 | public List getUrlsFromMessage(Message message, String linkText) throws Exception{ 206 | String html = getMessageContent(message); 207 | List allMatches = new ArrayList(); 208 | Matcher matcher = Pattern.compile("(]+>)"+linkText+"").matcher(html); 209 | while (matcher.find()) { 210 | String aTag = matcher.group(1); 211 | allMatches.add(aTag.substring(aTag.indexOf("http"), aTag.indexOf("\">"))); 212 | } 213 | return allMatches; 214 | } 215 | 216 | private Map getStartAndEndIndices(int max) throws MessagingException { 217 | int endIndex = getNumberOfMessages(); 218 | int startIndex = endIndex - max; 219 | 220 | //In event that maxToGet is greater than number of messages that exist 221 | if(startIndex < 1){ 222 | startIndex = 1; 223 | } 224 | 225 | Map indices = new HashMap(); 226 | indices.put("startIndex", startIndex); 227 | indices.put("endIndex", endIndex); 228 | 229 | return indices; 230 | } 231 | 232 | /** 233 | * Gets text from the end of a line. 234 | * In this example, the subject of the email is 'Authorization Code' 235 | * And the line to get the text from begins with 'Authorization code:' 236 | * Change these items to whatever you need for your email. This is only an example. 237 | */ 238 | public String getAuthorizationCode() throws Exception { 239 | Message email = getMessagesBySubject("Authorization Code", true, 5)[0]; 240 | BufferedReader reader = new BufferedReader(new InputStreamReader(email.getInputStream())); 241 | 242 | String line; 243 | String prefix = "Authorization code:"; 244 | 245 | while ((line = reader.readLine()) != null) { 246 | if(line.startsWith(prefix)) { 247 | return line.substring(line.indexOf(":") + 1); 248 | } 249 | } 250 | return null; 251 | } 252 | 253 | /** 254 | * Gets one line of text 255 | * In this example, the subject of the email is 'Authorization Code' 256 | * And the line preceding the code begins with 'Authorization code:' 257 | * Change these items to whatever you need for your email. This is only an example. 258 | */ 259 | public String getVerificationCode() throws Exception { 260 | Message email = getMessagesBySubject("Authorization Code", true, 5)[0]; 261 | BufferedReader reader = new BufferedReader(new InputStreamReader(email.getInputStream())); 262 | 263 | String line; 264 | while ((line = reader.readLine()) != null) { 265 | if(line.startsWith("Authorization code:")) { 266 | return reader.readLine(); 267 | } 268 | } 269 | return null; 270 | } 271 | 272 | 273 | 274 | //************* BOOLEAN METHODS ******************* 275 | 276 | /** 277 | * Searches an email message for a specific string 278 | */ 279 | public boolean isTextInMessage(Message message, String text) throws Exception { 280 | String content = getMessageContent(message); 281 | 282 | //Some Strings within the email have whitespace and some have break coding. Need to be the same. 283 | content = content.replace(" ", " "); 284 | return content.contains(text); 285 | } 286 | 287 | public boolean isMessageInFolder(String subject, boolean unreadOnly) throws Exception { 288 | int messagesFound = getMessagesBySubject(subject, unreadOnly, getNumberOfMessages()).length; 289 | return messagesFound > 0; 290 | } 291 | 292 | public boolean isMessageUnread(Message message) throws Exception { 293 | return !message.isSet(Flags.Flag.SEEN); 294 | } 295 | } 296 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Using Test Automation to Verify Emails 2 | Utility for verifying emails within test automation. Uses JavaMail API 3 | 4 | This utility can be used to verify that an email was received, verify its contents, open links within the email, extract data sent (temp passwords, verification codes, etc). 5 | 6 | Examples of usage can be found at http://angiejones.tech/test-automation-to-verify-email/ 7 | --------------------------------------------------------------------------------