Integration Testing with DevInbox

Learn how to integrate DevInbox into your automated test suites to verify email functionality in your applications. This guide covers common testing scenarios and best practices.

Why Use DevInbox for Integration Testing?

Fast & Isolated

Generate unique email addresses in milliseconds. Each test gets its own isolated mailbox, preventing test interference and ensuring reliable results.

Deterministic

No more flaky tests due to email delivery delays. DevInbox provides instant, reliable email capture for consistent test results.

Content Verification

Verify email content, extract structured data, and ensure emails follow your templates with powerful template matching capabilities.

Cost Effective

No need for real email services or complex email server setups. Start testing immediately with our generous free tier.

Quick Start

The basic integration test workflow follows three simple steps: create a temporary mailbox, trigger your application's email sending, and verify the email was received with the correct content.

1

Create a Temporary Mailbox

Use the API to generate a unique email address for your test

2

Trigger Email Sending

Execute your application logic that sends the email

3

Verify Email Content

Retrieve the message and assert it contains the expected content

Complete Integration Test Examples

Python Integration Test

import requests
def test_user_registration_sends_welcome_email():
    API_KEY = "your_api_key"
    headers = {"X-Api-Key": API_KEY}
    # Arrange - Create mailbox
    r = requests.post(
        "https://api.devinbox.io/mailboxes",
        headers=headers, json={})
    mailbox = r.json()
    test_email = f"{mailbox['key']}@devinbox.io"
    # Act - Trigger registration
    user_service.register(
        email=test_email,
        name="John Doe")
    # Assert - Verify email
    r = requests.get(
        f"https://api.devinbox.io/messages/{mailbox['key']}",
        headers=headers)
    messages = r.json()
    assert messages['count'] == 1
    assert "Welcome" in messages['messages'][0]['subject']

JavaScript Integration Test

const API_KEY = 'your_api_key';
const headers = { 'X-Api-Key': API_KEY };
test('user registration sends welcome email', async () => {
    // Arrange - Create mailbox
    const res = await fetch(
        'https://api.devinbox.io/mailboxes',
        { method: 'POST', headers });
    const mailbox = await res.json();
    const testEmail = `${mailbox.key}@devinbox.io`;
    // Act - Trigger registration
    await userService.register({
        email: testEmail,
        name: 'John Doe'
    });
    // Assert - Verify email
    const msgs = await fetch(
        `https://api.devinbox.io/messages/${mailbox.key}`,
        { headers });
    const messages = await msgs.json();
    expect(messages.count).toBe(1);
    expect(messages.messages[0].subject)
        .toContain('Welcome');
});

C# / .NET Integration Test

using System.Net.Http;
using System.Text;
using System.Text.Json;
[Test]
public async Task UserRegistration_SendsWelcomeEmail()
{
    var client = new HttpClient();
    client.DefaultRequestHeaders.Add(
        "X-Api-Key", "your_api_key");
    // Arrange - Create mailbox
    var response = await client.PostAsync(
        "https://api.devinbox.io/mailboxes",
        new StringContent("{}", 
            Encoding.UTF8, 
            "application/json"));
    var json = await response
        .Content.ReadAsStringAsync();
    var mailbox = JsonSerializer
        .Deserialize<JsonElement>(json);
    var testEmail = $"{mailbox.GetProperty("key")
        .GetString()}@devinbox.io";
    // Act - Trigger registration
    await _userService.RegisterAsync(new UserData
    {
        Email = testEmail,
        Name = "John Doe"
    });
    // Assert - Verify email
    var key = mailbox.GetProperty("key").GetString();
    var msgsResponse = await client.GetAsync(
        $"https://api.devinbox.io/messages/{key}");
    var msgsJson = await msgsResponse
        .Content.ReadAsStringAsync();
    var messages = JsonSerializer
        .Deserialize<JsonElement>(msgsJson);
    Assert.That(messages.GetProperty("count")
        .GetInt32(), Is.EqualTo(1));
    Assert.That(messages.GetProperty("messages")[0]
        .GetProperty("subject").GetString(),
        Does.Contain("Welcome"));
}

Go Integration Test

func TestUserRegistrationSendsWelcomeEmail(t *testing.T) {
    // Arrange - Create mailbox
    client := &http.Client{}
    req, _ := http.NewRequest("POST",
        "https://api.devinbox.io/mailboxes",
        bytes.NewBuffer([]byte("{}")))
    req.Header.Set("X-Api-Key", "your_api_key")
    resp, _ := client.Do(req)
    defer resp.Body.Close()
    var mailbox map[string]interface{}
    json.NewDecoder(resp.Body).Decode(&mailbox)
    testEmail := fmt.Sprintf("%s@devinbox.io",
        mailbox["key"])
    // Act - Trigger registration
    userService.Register(UserData{
        Email: testEmail,
        Name:  "John Doe",
    })
    // Assert - Verify email
    req, _ = http.NewRequest("GET",
        fmt.Sprintf(
            "https://api.devinbox.io/messages/%s",
            mailbox["key"]), nil)
    req.Header.Set("X-Api-Key", "your_api_key")
    resp, _ = client.Do(req)
    defer resp.Body.Close()
    var messages map[string]interface{}
    json.NewDecoder(resp.Body).Decode(&messages)
    assert.Equal(t, 1, 
        int(messages["count"].(float64)))
    msgList := messages["messages"].([]interface{})
    assert.Contains(t,
        msgList[0].(map[string]interface{})
        ["subject"], "Welcome")
}

Template-Based Verification

Advanced Content Verification

Use templates to verify email structure and extract specific data points automatically. Templates allow you to parse dynamic values like verification codes, user names, and other parameters.

Python Example with Template

def test_registration_extracts_verification_code():
    # Create mailbox and trigger email
    mailbox = create_test_mailbox()
    trigger_user_registration(
        f"{mailbox['key']}@devinbox.io")
    # Get message with template parsing
    r = requests.get(
        f"https://api.devinbox.io/messages/"
        f"{mailbox['key']}/user-welcome/single",
        headers={"X-Api-Key": API_KEY})
    parsed = r.json()
    user_name = parsed['subject']['user_name']
    verification_code = parsed['body']['verification_code']
    assert user_name == "John Doe"
    assert verification_code is not None

C# Example with Template

[Test]
public async Task Registration_ExtractsVerificationCode()
{
    // Create mailbox and trigger email
    var mailbox = await CreateTestMailbox();
    await TriggerUserRegistration(
        $"{mailbox["key"]}@devinbox.io");
    // Get message with template parsing
    var key = mailbox.GetProperty("key").GetString();
    var response = await client.GetAsync(
        $"https://api.devinbox.io/messages/"
        $"{key}/user-welcome/single");
    var json = await response
        .Content.ReadAsStringAsync();
    var parsed = JsonSerializer
        .Deserialize<JsonElement>(json);
    var userName = parsed.GetProperty("subject")
        .GetProperty("user_name").GetString();
    var verificationCode = parsed.GetProperty("body")
        .GetProperty("verification_code").GetString();
    Assert.That(userName, Is.EqualTo("John Doe"));
    Assert.That(verificationCode, Is.Not.Null);
}

Common Test Scenarios

Password Reset Flow

Test that password reset emails are sent and contain valid reset links.

// Request password reset
await authService.RequestPasswordResetAsync(testEmail);
// Get the last email
var response = await client.GetAsync(
    $"https://api.devinbox.io/messages/{key}/last");
var json = await response
    .Content.ReadAsStringAsync();
var email = JsonSerializer
    .Deserialize<JsonElement>(json);
Assert.That(email.GetProperty("subject")
    .GetString(), Does.Contain("Password Reset"));
Assert.That(email.GetProperty("body")
    .GetString(), Does.Contain("reset-password"));

Order Confirmation

Verify order confirmation emails contain correct order details.

// Process order
var orderId = await orderService.CreateOrderAsync(
    testEmail, orderItems);
// Verify with template
var response = await client.GetAsync(
    $"https://api.devinbox.io/messages/"
    $"{key}/order-confirmation/last");
var json = await response
    .Content.ReadAsStringAsync();
var parsed = JsonSerializer
    .Deserialize<JsonElement>(json);
Assert.That(parsed.GetProperty("body")
    .GetProperty("order_id").GetString(),
    Is.EqualTo(orderId.ToString()));

Multi-Recipient Notifications

Test that notifications are sent to all expected recipients.

// Create multiple test mailboxes
var mailboxes = await Task.WhenAll(
    Enumerable.Range(0, 3)
        .Select(_ => CreateTestMailbox()));
// Trigger notification
await notificationService.SendAlertAsync(
    "System Maintenance");
// Verify all received
foreach (var mailbox in mailboxes)
{
    var key = mailbox.GetProperty("key").GetString();
    var response = await client.GetAsync(
        $"https://api.devinbox.io/messages/"
        $"{key}/count");
    var json = await response
        .Content.ReadAsStringAsync();
    var count = JsonSerializer
        .Deserialize<JsonElement>(json)
        .GetProperty("count").GetInt32();
    Assert.That(count, Is.GreaterThan(0));
}

Best Practices

1

Use Temporary Mailboxes

Always use temporary mailboxes for tests. They're automatically cleaned up after 24 hours and don't count against your persistent mailbox quota.

2

Verify Message Count First

Check the message count before retrieving messages to ensure your test received the expected number of emails. Use /messages/{'{key}'}/single when expecting exactly one email.

3

Use Templates for Data Extraction

Create templates for emails with dynamic content. Templates make tests more maintainable and allow you to extract specific values like verification codes or order numbers.

4

Isolate Each Test

Create a new mailbox for each test to ensure complete isolation. This prevents tests from interfering with each other and makes debugging easier.

5

Handle Async Operations

DevInbox captures emails instantly, but your application might have some delay before sending. Add small delays or retries if needed, though usually emails arrive immediately.

Setting Up Your Test Environment

API Key Configuration

Store your DevInbox API key securely using environment variables:

 Linux/macOS
export DEVINBOX_API_KEY="your_api_key_here"
 Windows PowerShell
$env:DEVINBOX_API_KEY="your_api_key_here"

Test Framework Integration

Configure an HTTP client once in your test setup for reuse across tests:

[SetUp]
public void Setup()
{
    _client = new HttpClient();
    _client.DefaultRequestHeaders.Add(
        "X-Api-Key",
        Environment.GetEnvironmentVariable(
            "DEVINBOX_API_KEY"));
}

For Python, configure the requests library with default headers in your test fixtures.

Next Steps

Ready to start writing integration tests? Check out these resources to get started.