How to verify email delivery in Gmail inbox using automated testing

I’m working on a test automation project where our app sends emails to a specific Gmail account. I need to check if these emails actually arrive in the inbox as part of our automated tests.

Our tech stack includes Selenium, Java, and Maven. I’m looking for the best approach to verify email receipt in Gmail programmatically. The Gmail API seems like a viable option, but I’m open to other suggestions.

The main challenge I’m facing is handling authentication in the test scripts. I need to log into Gmail automatically without manual intervention.

For context, the emails I’m looking for have a specific pattern in the subject line, something like “[TPV:XXX] password reset notification for user”. I just need to confirm these emails show up in the inbox.

What would be the most reliable way to implement this? Any code examples or documentation references would be greatly appreciated.

I’ve handled similar testing setups before. A dedicated test Gmail account with OAuth2 service authentication is your best bet - way more reliable than trying to automate the web interface with Selenium. Skip logging into Gmail’s web interface entirely. Just authenticate directly with the Gmail API using service credentials in your test environment. Set up gmail.readonly scope (that’s all you need) and use Google’s Java client library. For finding emails, the API’s search works exactly like Gmail’s web search - same operators and everything. You can search by subject line pattern no problem. Couple things to watch for: emails don’t always arrive instantly during testing. I usually set up polling that checks every few seconds with a timeout. Also filter by date range so you don’t accidentally grab old test emails from previous runs.

gmail api is def the way to go, but watch out for rate limits - they can totally kill your test runs if ur not careful. I always set up a separate gmail account for testing and use 2fa with app passwords. way easier than dealing with oauth in ci/cd.

Try Gmail’s IMAP instead of the API - it’s way simpler to set up. IMAP works great for basic email verification tests and you don’t need to mess with OAuth. Just enable IMAP in your test account settings and use JavaMail API with your current Maven setup. Authentication is easy with app-specific passwords. For subject line pattern matching, IMAP search commands handle regex patterns well. Plus IMAP plays nicer with existing Java test frameworks. Just heads up - IMAP connections can be flaky in CI environments, so build in retry logic. Gmail’s IMAP also has some weird timing issues with folder sync, so add wait conditions between sending emails and checking for them.