Email Templates

Define email patterns with placeholders to verify structure and extract dynamic data from your application's emails. Templates make integration tests more reliable and maintainable.

What are Email Templates?

Email Templates are patterns that define the expected structure of your emails. They use placeholder syntax like {{UserName}} to mark dynamic content. When you verify an email against a template, DevInbox automatically extracts these values for assertion in your tests.

Verify Structure

Ensure emails follow the expected format and contain all required elements in the correct order.

Extract Data

Pull out dynamic values like verification codes, user names, or order numbers for validation.

Maintainable Tests

Write cleaner tests that focus on the data that matters, not fragile string matching.

How Templates Work

Template Syntax

Templates use double curly braces {{}} to define placeholders for dynamic content. The parser extracts values that match these placeholders when verifying an email.

Subject: Welcome to {{CompanyName}}, {{UserName}}!
Body:
Hello {{UserName}},
Welcome to {{CompanyName}}! 
Your verification code is: {{VerificationCode}}
Best regards,
The {{CompanyName}} Team

Matching Process

When you verify an email against a template, DevInbox's template parser:

  1. Converts the template pattern into a regular expression
  2. Matches the email content against this pattern
  3. Extracts values from the placeholders
  4. Returns extracted data as key-value pairs

Example: Before and After

Template Pattern

Welcome {{UserName}}! Code: {{Code}}

Actual Email

Welcome John Doe! Code: ABC123

Extracted: UserName = "John Doe" Code = "ABC123"

Sample Templates

User Welcome Email

A common template for welcome emails sent during user registration.

Template Name: user-welcome
Subject Pattern:
Welcome to {{CompanyName}}, {{UserName}}!
Body Pattern:
Hello {{UserName}},
Welcome to {{CompanyName}}! Your account has been
created successfully.
Verification Code: {{VerificationCode}}
Best regards,
The {{CompanyName}} Team

Password Reset Email

Template for password reset requests with time-sensitive links.

Template Name: password-reset
Subject Pattern:
Password Reset Request for {{UserName}}
Body Pattern:
Hello {{UserName}},
You requested a password reset. Click the link below:
{{ResetLink}}
This link expires in {{ExpiryHours}} hours.

Order Confirmation Email

Template for e-commerce order confirmations with order details.

Template Name: order-confirmation
Subject Pattern:
Order #{{OrderNumber}} Confirmation
Body Pattern:
Thank you for your order, {{CustomerName}}!
Order Number: {{OrderNumber}}
Total: ${{Total}}
We'll send you tracking information once shipped.

Using Templates in Integration Tests

Template API Endpoints

Use the endpoint /messages/{'{key}'}/{'{template}'}/single to retrieve and parse the most recent email matching your template. The API returns extracted values ready for assertions in your tests.

Python - Template Verification

import requests
def test_welcome_email_with_template():
    API_KEY = "your_api_key"
    headers = {"X-Api-Key": API_KEY}
    # Create mailbox
    r = requests.post(
        "https://api.devinbox.io/mailboxes",
        headers=headers, json={})
    mailbox = r.json()
    test_email = f"{mailbox['key']}@devinbox.io"
    # Trigger registration
    user_service.register(
        email=test_email,
        name="Jane Smith",
        company="Acme Corp")
    # Get parsed email using template
    r = requests.get(
        f"https://api.devinbox.io/messages/"
        f"{mailbox['key']}/user-welcome/single",
        headers=headers)
    parsed = r.json()
    # Extract and verify template values
    assert parsed['subject']['UserName'] == "Jane Smith"
    assert parsed['subject']['CompanyName'] == "Acme Corp"
    assert parsed['body']['VerificationCode'] is not None
    assert len(parsed['body']['VerificationCode']) == 6

JavaScript - Template Verification

const API_KEY = 'your_api_key';
const headers = { 'X-Api-Key': API_KEY };
test('welcome email with template', async () => {
    // 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`;
    // Trigger registration
    await userService.register({
        email: testEmail,
        name: 'Jane Smith',
        company: 'Acme Corp'
    });
    // Get parsed email using template
    const msgRes = await fetch(
        `https://api.devinbox.io/messages/`
        + `${mailbox.key}/user-welcome/single`,
        { headers });
    const parsed = await msgRes.json();
    // Extract and verify template values
    expect(parsed.subject.UserName).toBe('Jane Smith');
    expect(parsed.subject.CompanyName).toBe('Acme Corp');
    expect(parsed.body.VerificationCode).toBeDefined();
    expect(parsed.body.VerificationCode).toHaveLength(6);
});

C# / .NET - Template Verification

using System.Net.Http;
using System.Text;
using System.Text.Json;
[Test]
public async Task WelcomeEmail_WithTemplate()
{
    var client = new HttpClient();
    client.DefaultRequestHeaders.Add(
        "X-Api-Key", "your_api_key");
    // 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";
    // Trigger registration
    await _userService.RegisterAsync(new UserData
    {
        Email = testEmail,
        Name = "Jane Smith",
        Company = "Acme Corp"
    });
    // Get parsed email using template
    var key = mailbox.GetProperty("key").GetString();
    var msgResponse = await client.GetAsync(
        $"https://api.devinbox.io/messages/"
        + $"{key}/user-welcome/single");
    var msgJson = await msgResponse
        .Content.ReadAsStringAsync();
    var parsed = JsonSerializer
        .Deserialize<JsonElement>(msgJson);
    // Extract and verify template values
    var userName = parsed.GetProperty("subject")
        .GetProperty("UserName").GetString();
    var companyName = parsed.GetProperty("subject")
        .GetProperty("CompanyName").GetString();
    var verificationCode = parsed.GetProperty("body")
        .GetProperty("VerificationCode").GetString();
    Assert.That(userName, Is.EqualTo("Jane Smith"));
    Assert.That(companyName, Is.EqualTo("Acme Corp"));
    Assert.That(verificationCode, Is.Not.Null);
    Assert.That(verificationCode.Length, Is.EqualTo(6));
}

Go - Template Verification

func TestWelcomeEmailWithTemplate(t *testing.T) {
    // 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"])
    // Trigger registration
    userService.Register(UserData{
        Email:   testEmail,
        Name:    "Jane Smith",
        Company: "Acme Corp",
    })
    // Get parsed email using template
    req, _ = http.NewRequest("GET",
        fmt.Sprintf(
            "https://api.devinbox.io/messages/%s/"
            + "user-welcome/single",
            mailbox["key"]), nil)
    req.Header.Set("X-Api-Key", "your_api_key")
    resp, _ = client.Do(req)
    defer resp.Body.Close()
    var parsed map[string]interface{}
    json.NewDecoder(resp.Body).Decode(&parsed)
    // Extract and verify template values
    subject := parsed["subject"].(map[string]interface{})
    body := parsed["body"].(map[string]interface{})
    assert.Equal(t, "Jane Smith", 
        subject["UserName"])
    assert.Equal(t, "Acme Corp", 
        subject["CompanyName"])
    assert.NotNil(t, body["VerificationCode"])
    assert.Len(t, body["VerificationCode"].(string), 6)
}

Best Practices

1

Keep Templates Simple

Start with basic templates that capture essential fields. Avoid overly complex patterns that might break with minor formatting changes in your emails.

2

Use Descriptive Variable Names

Choose clear variable names that match your application's domain. Use {{VerificationCode}} instead of {{Code}} for clarity.

3

Test Template Matching First

Before using templates in your tests, verify they correctly match real emails from your application using the DevInbox dashboard or API.

4

Handle Whitespace Carefully

The template parser normalizes line endings but respects spacing. Be mindful of whitespace in your patterns, especially around placeholders.

5

Store Templates in Version Control

Keep your template definitions in your repository alongside your tests. This ensures templates evolve with your application and are accessible to all team members.

Advanced Tips

Multi-Line Content

Templates support multi-line patterns. The parser normalizes line endings, so your templates work consistently across different email formats.

Hello {{Name}},\n\nYour code is {{Code}}

Non-Greedy Matching

The template parser uses non-greedy matching for placeholders. If you have multiple placeholders in sequence, each captures the minimum text needed to satisfy the pattern.

Template Versioning

When your email format changes, create new template versions rather than updating existing ones. This prevents old tests from breaking unexpectedly.

Next Steps

Ready to use templates in your integration tests? Explore these resources to learn more.