How to Automate your Email Testing Part 2

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.

Step-by-step guide

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 my.email@gmail.com and then use my.email+alias01@gmail.com, my.email+alias02@gmail.com 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.

  1. So firstly, get yourself a free account
  2. Next, visit the mailbox settings and Enable IMAP on the Forwarding and POP/IMAP tab
  3. Now you’ll need to allow less secure apps on the account’s security settings – this lets us authorise our calls with an email/password combo, avoiding OAuth2.0

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

using (var smtpClient = new SmtpClient("smtp.gmail.com", 587))
{
    smtpClient.EnableSsl = true;
    smtpClient.Credentials = new NetworkCredential(<gmail_account>, <gmail_password>);
    smtpClient.Send("from@example.com", "to@example.com", "Dummy email 1", "Email for basic Gmail tests");
    smtpClient.Send("from@example.com", "to@example.com", "Dummy email 2", "Email for basic Gmail tests");
}

6. Now we can use ImapX to connect to the inbox

imapClient = new ImapClient("imap.gmail.com", 993, true);
imapClient.Behavior.AutoPopulateFolderMessages = true;
imapClient.Connect();
imapClient.Login(<gmail_account>, <gmail_password>);

7. Accessing our inbox is now simple

var inbox = imapClient.Folders.Inbox;
Assert.That(inbox.Exists == 2, "Should be a total of 2 emails as per test setup");

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”

var search = inbox.Search("SUBJECT Dummy email 1");

Assert.That(search.Length == 1, "Expected a single matching email");
Assert.That(search[0].To[0].Address, Is.EqualTo("to@example.com"));

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.

Leave a Reply

Your email address will not be published. Required fields are marked *