# TestFly Part 10: Email and 2FA testing with Mailhog, Mailtrap and IMAP

URL: https://hakangul.lovable.app/blog/testfly-part-10-email-and-2fa-testing-mailhog-mailtrap-imap
Author: Hakan Gül — Team Lead Senior Test Automation Engineer
Published: 2026-09-10
Updated: 2026-10-18
Category: test-automation
Tags: TestFly, Email Testing, Mailhog, Mailtrap, 2FA, Java, SDET

> Test signup, password reset and 2FA flows in Java with TestFly's built-in Mailhog, Mailtrap and IMAP mailbox clients.

## English

End-to-end tests for user registration, password resets and two-factor authentication (2FA) often fail because email delivery is awkward to test. TestFly ships mailbox clients for Mailhog, Mailtrap, Outlook Graph and generic IMAP. In one automated test you can fetch incoming email, pull an OTP code out with a regex and follow the verification link.

## Why email verification gets in the way of E2E tests

Almost every SaaS platform asks for email validation at signup or before sensitive operations. Automation suites usually have trouble with it:

- Public inboxes such as Gmail enforce rate limits, CAPTCHAs and bot detection.
- Developers often turn email verification off in test environments, so regressions in that flow reach production unnoticed.
- Third-party email libraries need MIME parsing, socket handling and hand-written wait loops.

TestFly puts an `email()` helper on `BaseTest`. It hides the protocol details and runs its asynchronous polling through the central `WaitEngine`.

## Connecting to a mailbox

Local mail catchers and enterprise cloud providers are both configured in `testfly.yml`:

```yaml title="testfly.yml"
email:
  provider: mailhog # options: mailhog, mailtrap, outlook, imap
  host: localhost
  port: 8025
  pollIntervalSeconds: 2
  timeoutSeconds: 30
```

## Testing signup with 2FA / OTP in Java

The example below signs up through the web UI, waits for the verification email, extracts the 6-digit OTP code and completes the login:

```java
package io.testfly.examples.email;

import io.testfly.email.EmailMessage;
import io.testfly.test.BaseTest;
import org.testng.annotations.Test;

public class EmailVerificationTest extends BaseTest {

    @Test
    public void testUserRegistrationWithEmailConfirmation() {
        String testEmail = "user_" + System.currentTimeMillis() + "@testfly.local";

        // 1. Fill registration form on WebUI
        open("/register");
        find("#email-input").type(testEmail);
        find("#submit-btn").click();

        // 2. Wait for confirmation email to arrive
        EmailMessage message = email().waitForMessage(query -> 
            query.to(testEmail).subjectContains("Welcome to TestFly")
        );

        // 3. Extract OTP code or activation link via Regex
        String otpCode = message.extractRegex("Your verification code is: (\\d{6})");

        // 4. Enter OTP in browser and confirm
        find("#otp-input").type(otpCode);
        find("#verify-btn").click();

        assertThat(find("#welcome-banner")).isVisible();
    }
}
```

## Supported mail providers

| Provider | Protocol | Typical Use Case |
|:---|:---|:---|
| **Mailhog** | HTTP REST API | Local Docker environments, CI/CD runners |
| **Mailtrap** | REST API & SMTP | Staging environments, shared team sandboxes |
| **Outlook Graph** | Microsoft Graph API | Enterprise Office 365 test mailboxes |
| **Generic IMAP** | SSL/TLS IMAP | Custom corporate email servers |

## FAQ

### Does TestFly poll the mailbox asynchronously?

Yes. It checks the inbox at a configurable interval until a message matching your criteria arrives or the timeout runs out.

### Can I extract HTML links and click them directly?

Yes. `message.extractLink("Confirm Email")` returns the verification URL, and you can go to it right away with `open(url)`.

### Does this work with temporary throwaway email addresses?

Yes. Generate dynamic inbox aliases (for example `user+123@domain.com`) and filter for them with `query.to(...)`.

## Türkçe

Kullanıcı kaydı, şifre sıfırlama ve iki faktörlü kimlik doğrulama (2FA) akışları uçtan uca testlerin en sık takıldığı yerlerdir. TestFly; Mailhog, Mailtrap, Outlook Graph ve genel IMAP için hazır istemcilerle geliyor. Gelen kutusunu sorgulamak, OTP kodunu regex ile ayıklamak ve doğrulama linkine gitmek tek satırlık çağrılarla yapılıyor.

## E-posta doğrulaması E2E testlerini neden zorlar

Modern web uygulamalarının neredeyse hepsi kayıt sırasında ya da hassas işlemlerde e-posta onayı ister. Klasik otomasyon projelerinde bu şu sorunları çıkarır:

- Gmail, Outlook gibi gerçek sağlayıcılar bot koruması, CAPTCHA ve istek sınırı uygular.
- Ekipler test ortamlarında e-posta doğrulamasını çoğu zaman kapatır. Böylece canlıdaki güvenlik açıkları ve regresyonlar gözden kaçar.
- Harici kütüphaneler karmaşık MIME ayrıştırma kodu ve elle yazılmış `Thread.sleep()` döngüleri gerektirir.

TestFly'da bu işi `BaseTest` üzerinden doğrudan çağırabileceğiniz `email()` yardımcısı üstlenir.

## TestFly e-posta sunucusuna nasıl bağlanır

Sağlayıcıyı `testfly.yml` dosyasına ekleyeceğiniz tek bir blokla tanımlarsınız:

```yaml title="testfly.yml"
email:
  provider: mailhog # mailhog, mailtrap, outlook, imap
  host: localhost
  port: 8025
  pollIntervalSeconds: 2
  timeoutSeconds: 30
```

## 2FA / OTP doğrulama senaryosu nasıl yazılır

Aşağıdaki test arayüzde kayıt formunu dolduruyor, gelen kutusunu dinliyor, 6 haneli doğrulama kodunu alıyor ve kodu tarayıcıya girerek işlemi tamamlıyor:

```java
package io.testfly.examples.email;

import io.testfly.email.EmailMessage;
import io.testfly.test.BaseTest;
import org.testng.annotations.Test;

public class EpostaDogrulamaTesti extends BaseTest {

    @Test
    public void kullaniciKaydiVeIkiFaktorluDogrulama() {
        String testEpostasi = "test_" + System.currentTimeMillis() + "@testfly.local";

        // 1. Kayıt formunu doldur
        open("/register");
        find("#email-input").type(testEpostasi);
        find("#submit-btn").click();

        // 2. Gelen doğrulama e-postasını bekle
        EmailMessage eposta = email().waitForMessage(sorgu -> 
            sorgu.to(testEpostasi).subjectContains("TestFly Hoş Geldiniz")
        );

        // 3. Regex ile 6 haneli OTP kodunu ayrıştır
        String otpKodu = eposta.extractRegex("Doğrulama kodunuz: (\\d{6})");

        // 4. Kodu tarayıcıya gir ve doğrula
        find("#otp-input").type(otpKodu);
        find("#verify-btn").click();

        assertThat(find("#welcome-banner")).isVisible();
    }
}
```

## Desteklenen e-posta sağlayıcıları

| Sağlayıcı | Protokol | Kullanım Alanı |
|:---|:---|:---|
| **Mailhog** | HTTP REST API | Lokal Docker ortamları, CI/CD pipeline'ları |
| **Mailtrap** | REST API & SMTP | Staging ve paylaşımlı test ortamları |
| **Outlook Graph** | Microsoft Graph API | Kurumsal Office 365 e-posta hesapları |
| **Genel IMAP** | SSL/TLS IMAP | Özel şirket içi e-posta sunucuları |

## SSS

### TestFly gelen kutusunu asenkron olarak bekler mi?

Evet. `email().waitForMessage()`, kriterlere uyan e-posta gelene kadar arka planda asenkron sorgulama yapar. Süre dolarsa açıklayıcı bir hata verir.

### E-postadaki onay butonuna doğrudan tıklanabilir mi?

Evet. `eposta.extractLink("Hesabımı Onayla")` HTML içindeki linki yakalar, `open(link)` ile de doğrudan o sayfaya gidersiniz.

### Dinamik e-posta takma adları (alias) kullanılabilir mi?

Evet. `kullanici+test1234@alanadi.com` gibi adresler üretip `sorgu.to(...)` filtresiyle yalnızca o adrese gelen postayı yakalayabilirsiniz.
