# Appium email MFA testing

How to receive email and open firebase verification links in Appium tests.

Appium is crucial tool in mobile QA and integration testing and many teams use Appium with Selenium to test Android applications end-to-end. Most applications have a sign-up process and testing this with real email accounts is essential for reliable app deployments. In this tutorial we'll show you how to create disposable email accounts, connect them to your Appium tests and then receive verification codes to confirm an account.

> Full code for this tutorial can be [found on GitHub](https://github.com/mailslurp/examples/tree/master/android-mailslurp-examples)

## Why test MFA?

Authentication providers like Firebase commonly use email based account verification or MFA. This typically involves sending a new user a unique link that must be opened in order to validate an account sign-up. Testing this process is the best way to ensure critical aspects of an app are functioning correctly. We can do this with temporary mailboxes with the free service MailSlurp.

## An example application

Let's write a test for an example application. Our test app uses Firebase Auth UI to allow user sign-up using email and password. After signing up the user is presented with a confirmation screen and must open their email and click a link to complete the sign-up. The app looks like this:

![](/assets/android-test-read-email/test-1.png)

In order to test this we will use Appium, Selenium, and MailSlurp to integrate disposable mailboxes that expire after each run and provide a unique user for every test.

## Testing user sign-up link

Okay, let's get started. First, we will assume you have Android studio setup with Appium installed (if not see the [github repository](https://github.com/mailslurp/examples/tree/master/android-mailslurp-examples)). Next add the `mailslurp-client-java` package from [Maven central](https://central.sonatype.com/artifact/com.mailslurp/mailslurp-client-java) to your build.gradle.kts.

## Add MailSlurp dependencies

Add the MailSlurp client to your dependencies file so we can control emails.



```kotlin
implementation("com.mailslurp:mailslurp-client-java:16.1.3")
```



Then in tests import the client like so:



```kotlin
import com.mailslurp.clients.ApiClient
import com.mailslurp.apis.*
import com.mailslurp.models.*
```



## Appium driver setup

Now inside a typical Appium test we might have a setup like this:



```kotlin
private lateinit var driver: AndroidDriver

@Before
fun setup() {
    val opts = UiAutomator2Options().apply {
        // install the debug APK before starting the session
        val projectRoot = File(System.getProperty("user.dir"))
        val apkFile = File(projectRoot, "build/outputs/apk/debug/app-debug.apk")
        require(apkFile.exists()) {
          "APK not found at ${apkFile.absolutePath}, run `./gradlew assembleDebug` first."
        }
        setApp(apkFile.absolutePath)
        setDeviceName("Android Emulator")
        setPlatformName("Android")
        setAutomationName("UiAutomator2")
        setAppPackage("dev.mailslurp.examples")
        setAppActivity("dev.mailslurp.examples.EntryChoiceActivity")
        setNoReset(true)
        setNewCommandTimeout(Duration.ofSeconds(300))
    }
    driver = AndroidDriver(URL("http://127.0.0.1:4723/wd/hub"), opts)
    driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10))
}
```



This will open the test application using the Appium selenium hub. We must enable that hub before each test run in another terminal. We use a Makefile like so:

```
ANDROID_HOME ?= $(HOME)/Library/Android/sdk
ANDROID_SDK_ROOT ?= $(ANDROID_HOME)

.PHONY: test-espresso

node_modules:
	npm install
	npx appium driver install uiautomator2

start-appium: node_modules
	ANDROID_HOME=$(HOME)/Library/Android/sdk ANDROID_SDK_ROOT=$(HOME)/Library/Android/sdk \
	npx appium --base-path /wd/hub
```

## Testing user sign up link

Next we can test our application sign up. Let's go!

### Open the app

First we will load the activity:



```kotlin
// open the app wait to load
driver.findElement(AppiumBy.id("dev.mailslurp.examples:id/item_launch_button"))
    .click()
```



We should see a sign-up form waiting for an email and password.

### Create disposable inbox

Next we create a new email account by using the MailSlurp inbox controller:



```kotlin
// create a disposable email account
val mailSlurpConfig = ApiClient().apply {
    setApiKey(MAILSLURP_API_KEY!!)
    readTimeout = 120_000
    writeTimeout = 120_000
    connectTimeout = 120_000
}
val inboxCtrl = InboxControllerApi(mailSlurpConfig)
val inbox = inboxCtrl.createInboxWithOptions(CreateInboxDto().expiresIn(300_000)).execute()
val testEmail = inbox.emailAddress
val testPwd = "test-password-${System.currentTimeMillis()}"
```



This is a real email account that can receive emails like those 2FA links sent by Firebase Auth. Next we can open that email and extract out the link.

> MailSlurp is free you just need a valid [API KEY](https://app.mailslurp.com)

### Submit user sign-up

Now we submit the email account and dummy password to simulate user sign-up. Here we fill the form inputs with the recently created email address and a random password then click "create account".



```kotlin
driver.findElement(AppiumBy.id("dev.mailslurp.examples:id/fieldEmail"))
    .sendKeys(testEmail)
driver.findElement(AppiumBy.id("dev.mailslurp.examples:id/fieldPassword"))
    .sendKeys(testPwd)
driver.findElement(AppiumBy.id("dev.mailslurp.examples:id/emailCreateAccountButton"))
    .click()
```



This is what a filled form looks like. You can see a randomized email account in the user field.

![create temp inbox for android](/assets/android-test-read-email/test-2.png)

After submitting we can expect an email to be sent to the inbox. Let's read it.

### Wait for email to arrive

In the next step we use MailSlurp [wait for methods](/docs/wait-for/) to hold the test open until the email is received by MailSlurp in the background.

![test user sign up](/assets/android-test-read-email/test-4.png)

After clicking the verify button an email is sent and we use the Wait controller to wait for a matching email in the test inbox:



```kotlin
driver.findElement(AppiumBy.id("dev.mailslurp.examples:id/verifyEmailButton"))
    .click()
val waitCtrl = WaitForControllerApi(mailSlurpConfig)
val email = waitCtrl.waitForLatestEmail()
    .inboxId(inbox.id)
    .timeout(120_000)
    .unreadOnly(true)
    .execute()
assertTrue(email.subject!!.contains("Verify your email"))
```



You can see at the end we verify the email arrived and has expected subject.

### Open email in Appium

Now we can extract the link from the email body using the MailSlurp [email controller](https://java.mailslurp.com/). After fetching the link we can open it in a chrome browser using the `driver.executeScript` using the deep link method:



```kotlin
// get links in email
val link = EmailControllerApi(mailSlurpConfig)
    .getEmailLinks(email.id)
    .execute()
    .links.first()

// open the verification link in Chrome via mobile deep link
@Suppress("UNCHECKED_CAST")
driver.executeScript(
  "mobile: deepLink",
  mapOf(
    "url" to link,
    "package" to "com.android.chrome",
    "newTask" to true
  )
)

// wait for JS to load
Thread.sleep(5_000)
// then go back to app
driver.activateApp("dev.mailslurp.examples")
```



It's a little unusual but it works! The link url loads in a browser and tells us the user is now verified.

![test user sign up](/assets/android-test-read-email/test-5.png)

### Verify user is confirmed

Wonderful! Lastly, we can navigate back to our test application and see that the user account is now showing confirmed.



```kotlin
val status = driver.findElement(AppiumBy.id("dev.mailslurp.examples:id/status"))
    .text
assertEquals("Email User: $testEmail (verified: true)", status)
```



Wow! We just tested email verification in appium. We used MailSlurp's free email accounts to receive the confirmation and opened the email link using the selenium driver.

## Test a one-time code login in Appium

Many apps sign users in with a six-digit code instead of a link. The user asks for a code, switches to their inbox and types the code into the app. Your Appium test has to do the same: wait for the new email in the test user's inbox, read the code from the message and enter it on the app's code screen.

Use the inbox you created for the test user. After the app sends the code, wait for the newest unread email and match the first six-digit number in its body:

```kotlin
// wait for the sign-in code email in the test user's inbox
val codeEmail = WaitForControllerApi(mailSlurpConfig)
    .waitForLatestEmail()
    .inboxId(inbox.id)
    .timeout(60_000)
    .unreadOnly(true)
    .execute()

// read the six-digit code from the message body
val code = Regex("""\b\d{6}\b""").find(codeEmail.body.orEmpty())?.value
checkNotNull(code) { "No 6-digit code in '${codeEmail.subject}'" }

// type the code into your app and submit it
driver.findElement(AppiumBy.id("com.example.app:id/codeInput")).sendKeys(code)
driver.findElement(AppiumBy.id("com.example.app:id/verifyButton")).click()
```

Replace the two element IDs with the ones on your app's code screen, then assert that the app shows the signed-in screen, as the sign-up test does above. Because the wait only returns unread email, a test that requests a second code reads the new message rather than the first one.

If your app sends the code by text message, give the test user a [MailSlurp phone number](/mobile/receive-sms-api/) and wait for the latest SMS on that number in the same way. Detox and other JavaScript test runners can make the same calls with the [MailSlurp JavaScript client](/docs/js/).

## Email in your appium tests

You can add temp email accounts and open real email during your Appium QA tests to ensure your apps key processes are functional. That means user sign-up, password reset, and real notifications. If you use Firebase auth or any other MFA auth provider check out [MailSlurp](/) today.
