
Test Automation Utility to Verify Email
Many applications send its users emails as part of the process flow but it’s not obvious how to use Selenium WebDriver to verify email. This is of course possible, but automating UI steps of a 3rd-party email application is not the most optimal approach. Because of this, I worked on a project once where we simply skipped the verification of the email receipt. This always bothered me, so I eventually blocked out some time to research how I might be able to automate the verification of email.
I found the JavaMail API. This is an absolute life saver! With this, I’ve been able to not only verify that an email was received, but also verify its contents, open links within the email, extract data sent (temp passwords, verification codes, etc). Someone recently asked me about email verification within automation, so I decided to open source the utility methods I’ve written that use the JavaMail API.
This is written to work for Gmail accounts. I’ve also tweaked this in past projects to work for Outlook accounts as well, so that’s definitely possible.
Downloading the Dependencies
Here are the dependencies that I add to my maven project. These go inside of pom.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<dependency> <groupId>javax.mail</groupId> <artifactId>javax.mail-api</artifactId> <version>1.5.5</version> </dependency> <dependency> <groupId>com.sun.mail</groupId> <artifactId>smtp</artifactId> <version>1.6.0</version> </dependency> <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>1.6.0</version> </dependency> |
Setting Email Properties
There’s quite a few properties that need to be set. It’s cleaner to put this in a properties file as opposed to directly in the code, but that would work just as well. Here’s my email.properties file which is located in a resources folder in my project.
1 2 3 4 5 6 |
mail.smtp.host=smtp.gmail.com mail.smtp.socketFactory.port=465 mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory mail.smtp.auth=true mail.smtp.port=465 mail.transport.protocol=smtp |
Utility Class
All interactions with the email application are contained in this EmailUtils.java class. Tests can then call any method needed.
I start by defining a private Folder object which represents the current folder that we’re reading from. I also created an enum of possible folders my application’s emails may be found in. This can be expanded to any other folders that exist in the email application.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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; } } |
Next, I provide multiple constructors. All of these may not necessary in most cases, but I wanted to be as flexible as possible to allow for the use of another properties file that holds the email account authentication data, and also provide a constructor that allows you to just pass the data in.
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 |
/** * 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); } |
If you’d like to store the email credentials in a properties file, you can add methods to be able to retrieve them. These are needed for the second constructor.
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 |
//************* 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"); } |
Here are methods to interact and/or read info from the email folder
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 |
//************* 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 { StringBuffer buffer = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(message.getInputStream())); String line; while ((line = reader.readLine()) != null) { buffer.append(line); } return buffer.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; } |
Boolean methods helpful for verification
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
/** * 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); } } |
Parsing methods can also prove helpful. For example, if your application sends out an authorization code that you need to retrieve to verify or continue on with your testing, you can use the method below to parse it out. Here’s an example where the data you want to parse is on the same line with other text.
Example Email
Subject: Authorization Code
Dear JANE DOE:
The authorization code you requested is listed below.
Authorization code:870632
Please note that this code is temporary. If you try entering the authorization code and it has expired, you’ll need to request a new one.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
/** * 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; } |
There could also be the case where the data you need to parse is on its own line. In that case, the method would be slightly different.
Subject: Authorization Code
Dear JANE DOE:
The authorization code you requested is listed below.
Authorization code:
870632
Please note that this code is temporary. If you try entering the authorization code and it has expired, you’ll need to request a new one.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
/** * 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; } |
EmailUtils.java in its entirety
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); } } |
Using the Utility in Tests
All of the following methods are example test methods that would go in another class, such as EmailTests.java
Connect to Email
1 2 3 4 5 6 7 8 9 10 11 |
private static EmailUtils emailUtils; @BeforeClass public static void connectToEmail() { try { emailUtils = new EmailUtils("YOUR_USERNAME@gmail.com", "YOUR_PASSWORD", "smtp.gmail.com", EmailUtils.EmailFolder.INBOX); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.getMessage()); } } |
Example of test using verification code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
@Test public void testVerificationCode() { try { //TODO: Execute actions to send verification code to email String verificationCode = emailUtils.getAuthorizationCode(); //TODO: Enter verification code on screen and submit //TODO: add assertions } catch (Exception e) { e.printStackTrace(); Assert.fail(e.getMessage()); } } |
Example of test verifying that email contains a specific text
Notice the call to getMessagesBySubject. This utility method allows you to indicate whether you only want to get unread messages or not. This is very helpful for tests that are running repeatedly. This ensures you’re not looking at an older message from a previous run.
The third argument here, 5, is the max number of messages to look through to find this email message. This also helps ensure you’re only looking at the latest messages, and also speeds up the test by limiting the search and avoiding going through the entire folder.
getMessagesBySubject returns an array of Message objects, so the test uses an index to get the first one (which would be the latest one in the email folder)…the one we want.
1 2 3 4 5 6 7 8 9 10 |
@Test public void testTextContained() { try{ Message email = emailUtils.getMessagesBySubject("Loan Approval", true, 5)[0]; Assert.assertTrue("Approval message is not in email", emailUtils.isTextInMessage(email, "You have been approved")); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.getMessage()); } } |
Go to link within email
The utility method getUrlsFromMessage will return a list of links contained within the email. This method can of course be used to verify the link’s existence, but coupling this with Selenium WebDriver, you can also go to the link if you need to do further verification.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
@Test public void testLink() { //TODO: apply for a loan using criteria that will result in the application being rejected try{ Message email = emailUtils.getMessagesBySubject("Decision on Your Loan Application", true, 5)[0]; String link = emailUtils.getUrlsFromMessage(email, "Click here to view the reason").get(0); driver.get(link); //TODO: continue testing } catch (Exception e) { e.printStackTrace(); Assert.fail(e.getMessage()); } } |
There are many more methods in the EmailUtils class that can prove useful for your automation needs. The utility class is on Github, so can be downloaded and/or contributed to.
Troubleshooting
Gmail has gotten stricter about third party applications accessing their services. I’ve noticed recently, Gmail will block the authorization and you’ll see an error like this
Please log in via your web browser and then try again
Additionally, you may also get an email from Gmail alerting you that the API is trying to access your account and has been blocked.
To resolve this, you’ll need to change your settings within Gmail to allow access to less secure accounts. Note that this makes the account more susceptible to attacks, so I wouldn’t recommend doing this on your corporate or even personal account. Ensure you’re using an account set up just for testing which holds no sensitive data.
Alister Scott
We use a service called Mailosaur which built straight for this purpose and allows full API access to all emails and JSON objects to easily retrieve content. We found using GMail too unreliable due to Google constantly blocking and shutting down the account for API access. See my blog post: https://watirmelon.blog/2016/02/15/testing-email-in-e2e-tests-with-mailosaur/
Jithin Mathew
Hi Angie, Nice tutorial.
I have a suggestion. A disposable web mail applications will also do the same job. We can get the message content by using their API’s. This one is an open source.
http://www.inbucket.org.
Greg
Thanks for recommending inbucket. I’ll try it out since Gmail sometimes messes up my automation workflow with their random verification of recovery info.
Rohit
Hi , How do you actually send Emails to inbuket from your application . We have a application which sends emails via a service(that belongs to some security team) to whatever email we set via the UI . How then can I send emails to inbucket . I tried to ask my IT Team if they could set a autoforward rule in my microsoft exchange so that when my application sends email to me it gets routed to this local smtp server.But they are not agreeing to this ? Is there any other alternative ?
Luke
I use Putbox.com which allows me to send an email to anyemail@putbox.com then hit the website itself to grab the email and get/verify whatever I need in it. It’s a nice simple, fast, and free option for verifying email.
Vinodh
Hi Angie, Nice to read this article. Email testing involves 2 step process (viz) triggering email templates for set of users from 3rd party tool & verifying the triggered email in multiple email clients/browsers which involves content check against your template source (HTML/PDF), images, links & alt-tag info. I see this covers part1 only, have you done the other part.
We have done this end-to-end implementation, just want to know if you have any solution for alignment check visually.
Our tech stack has BOX API for content check against source, Java and Selenium. Let me know if you have any solution.
Regards,
Vinodh
@vinu015
siva
What are the changes need to do in order to work with outlook?
Mircea Cocosila
Hi Angie,So nice that you open source your email verification utility. You said ” I’ve also tweaked this in past projects to work for Outlook accounts as well, so that’s definitely possible. ” Could you please also open source the variant that works with Outlook?Thanks,mircea
Angie Jones
Mircea, all you should have to do is change the properties in email.properties. Mine are set for gmail but you would change yours for Outlook. Here’s a resource that shows where to get the Outlook values:
Rohit T
Hi Angie/Mircea,
Sandy
Hi,
I am trying to do the same where i am trying to verify the incoming mails to my official outlook using java code. I am able to send mails using smtp but tried a lot, still failing to verify incoming mails into my official outlook account. Please let me know if u can help here.
Adil A Chaudry
Hi Angie,
Veer
Hi Angie. Thanks a lot for sharing this. Do you have the code in any repositories like Git that you can share?
Angie Jones
yep
https://github.com/angiejones/email-test-automation
Svetlana Petrenko
Thank you, Angie, you saved my week. Very nice tutorial!
Ruchi Saklani
Hi Angie, I am getting following error, can you please help me out – javax.mail.MessagingException: Connection timed out: connect; nested exception is: java.net.ConnectException: Connection timed out: connect at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:670) at javax.mail.Service.connect(Service.java:295) at javax.mail.Service.connect(Service.java:176) at utils.EmailUtils.<init>(EmailUtils.java:85)
Aathi
Hey Ruchi,I faced the same issue and later found out to be the network issue, try configuring Fire wall rules (inbound and outbound rules) for the port which you are trying to communicate ( 993 for imap). Thanks
Shehani Hew
Hi Aathi,
Krishna Chaitanya
Thanks!!! This article has really increase the scope of automation.
Dima
Thank you so much, you’re awesome !!!
Bhushan
Hi Angie, Your article is really helpful. I wanted to know why have you used SMTP instead of IMAP.Thanks
Aathi
Hi Angie,I am trying this method Go to link within email, but getting an error – java.lang.ArrayIndexOutOfBoundsException: 0, can you tell me where am i going wrong?
Bharath
Hi Angie,java.lang.ArrayIndexOutOfBoundsException: 0I am getting this error inspite of having emails in the mailbox.I want know the reason am I missing on something.Thanks
Angie Jones
Make sure you’re indicating the right folder (e.g. INBOX)
Rohit Vatta
I also saw this error message. The indices is calculated wrongly. I could see count of emails as 62000 but the getTotalMessagesCount comes out as 100000;
Ashmi
I also get this error: java.lang.ArrayIndexOutOfBoundsException: 0
Amna
I was having the same error what I did is that I have added a wait condition for 10 sec incase my code is running fast than receiving the mail
jp
it is resolved for my update the this line.
Message email = getMessagesBySubject(sub, true, getNumberOfMessages())[0];
try this. hope it will resolved your java.lang.ArrayIndexOutOfBoundsException: 0 issue
Atif
Thanks for sharing your solution Angie. Do you have or know of any similar solution for C#?
Thomas Knee
Hi Angie,In the “Connect To Email” code snippet, shouldn’t the host be pop3 or imap instead of smtp as you are retrieving incoming emails rather than sending outgoing ones, or am I totally missing something?Cheers,-Thomas
Rodrigo
Hi Angie:
Rodrigo
Hi Again, Angie:
Angie Jones
can you send me an example of the email you’re trying to test and tell me the code you’re trying to extract out?
WYS
Please use below code to verify your email address.1234Can I know why I’m receiving the result as null?Please help me out to solve this.
Sandy
Hi, Angie,
I am trying to automation the scenario where i have to verify an incoming mail and extract the subject from it into my official outlook account. I am able to send one using the smtp protocol in java code but failed to verify an incoming mail in outlook.
Please help if you can
satish parimi
Hi Angie,
Viji
Please look at troubleshooting section.
Radha Reddy
Pipul
Angie while I’m retrieving the email I’m not getting the exact content. When extracting I’m getting amp sign as well I’m getting extra character when using the same function. Can you tell me a solution for this?
Asma Razaq
Angie Jones
Probably with something like Twilio
Omprakash
Good solution, however Google’s OAuth2 is better due to Google’s security restrictions that might break automation. I believe even for OAuth2, you have to authenticate once manually in order to make it work.
Dung
This code is great but I have a question. I’m realizing that this code gets latest emails by the first email in the list of email. However when I want to get the latest message from emails that are sent by only one person, it gets the first email, this is not my expectation. I want to get the latest one. How can I get the latest one in this case?
Jeff
Oleksandr Iavgel
Hello Angie,
Maria Feier
Hello,
Asserted
Hi Angie,
Vivek Rathod
Awesome! Thanks for writing this Angie, very helpful article
Gummadi Kalyan
Hi Angie,
Anisha Raju
Could you please share this through your Youtube channel. So that we can visualize each steps
David Tran
Hi Angie,
Bhavesh Soni
Manoj
I used the below code to login in to my gmail account but getting the exception javax.mail.AuthenticationFailedException: [AUTHENTICATIONFAILED] Invalid credentials (Failure) however when i try to login manually it is working fine.
Michelle Cortes
Hi Angie, thanks for this article, found this to be really sensible and easy to understand. However when I tried doing this in my Selenium Webdriver- Java project that aims to verify an outlook email, I have a number of import that returns an unresolved error, which causes a huge chunk of the code to not work.
Waqas Raza
Hey,
Cindy
Hey,
When i click on the link using getUrlsFromMessage() it’s not getting the exact url present in the email and the link has append with some other characters like ‘=3D%”. How do I resolve this issue?
Amna
Try to do some string operations like split, substring, join etc. to get the desired link
prasad
hey.
i am getting the below error please help me to get out of this
javax.mail.MessagingException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target;
nested exception is:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
Nhi
Yes I’m facing the same issue. I resolve it by adding the server certificate to JDK’s keystore. You can see more details here how to do it https://www.mkyong.com/webservices/jax-ws/suncertpathbuilderexception-unable-to-find-valid-certification-path-to-requested-target/
Aalaa Osama
Dear Angie,
I hope you are fine ,
Thanks for this article it is amazing .
I need to ask a question about
Do you have example for [sent]
I replace inbox by sent in the example above and i get error that don’t find sent
selenium_123
Hi, I am not able to extract particular link from the email content, I need to extract it and click on it. Can you please let me how to do it?
Sahana
Hello Angie
Thank you for this wonderful effort. I am trying to work on this but I’m lost. I’m using the cucumber java framework and I don’t know where to put the config file. Also if someone from here can also help me run this on Jenkins (Linux-based) please?
Thanks,
Sahana
Geeta S H
Hi, Thank you for this article. I’m trying this but getting exception: javax.mail.AuthenticationFailedException:
Please suggest me some solutions.
Siva
You might configured 2 factor authentication for Gmail. try to enable this https://myaccount.google.com/lesssecureapps
Prabhu
How can i ignore electronic message
IMPORTANT – PLEASE READ: This electronic message, including its attachments, is CONFIDENTIAL and may contain PROPRIETARY or LEGALLY PRIVILEGED or PROTECTED information and is intended for the authorized recipient of the sender. If you are not the intended recipient, you are hereby notified that any use, disclosure, copying, or distribution of this message or any of the information included in it is unauthorized and strictly prohibited. If you have received this message in error, please immediately notify the sender by reply e-mail and permanently delete this message and its attachments, along with any copies thereof, from all locations received (e.g., computer, mobile device, etc.). To the extent permitted by law, we may monitor electronic communications for the purposes of ensuring compliance with our legal and regulatory obligations and internal policies. We may also collect email traffic headers for analyzing patterns of network traffic and managing client relationships. For further information see our privacy-policy. Thank you.
Please suggest me some solutions.