In part 1 of this guide we looked at how we can use Mailtrap.io to intercept our SMTP traffic before our emails are sent out. In this section we’re going to use IMAP to talk to our Gmail account, offering more of an end-to-end test, as well as covering cases where the SUT doesn’t call SMTP directly.
Part 2: Using IMAP with Gmail
Gmail is great for a number of reasons, it’s free for a start, but a huge benefit for testing is the ability to use a single account with dynamic aliased addresses. You can create firstname.lastname@example.org and then use email@example.com, firstname.lastname@example.org etc. Another option is to use a service like Mailinator but this will set you back $1500/year if you want programmatic access via their API.
4. That should be everything that’s needed with the email account, now we need a way to talk to the IMAP service. Once again, I’ll be working in C# with the ImapX library
5. Again, we’ll want to populate our inbox with a few emails – thankfully we can also use Gmail as our SMTP server to post messages
6. Now we can use ImapX to connect to the inbox
7. Accessing our inbox is now simple
8. You’ll likely want to search your inbox and this is done by supplying an IMAP search query, these can be strung together e.g. “TO <email> SUBJECT Dummy email 1”
9. Finally a little cleanup
So there you have it, programmatic access to a dynamic email address for use in your integration and end to end tests. Again you can find some sample code over in Bitbucket including some interactions with the Google dotnet SDK and S22, an alternative dotnet IMAP client.