# Find and retrieve content within emails

MailSlurps dashboard and API offer numerous ways to filter and extract content and attachments from emails.

You can also use MailSlurp to find patterns in email contents and extract text matches for later use. Examples might be testing user sign up verification processes or customized transactional emails.

# Extracting content

You can use the email controller getEmailContentMatch method to extract matching text from an email.

it('can extract email content', async () => {
    const mailslurp = new MailSlurp(config);
    const inbox1 = await mailslurp.createInbox();
    const inbox2 = await mailslurp.createInbox();
    const to = [inbox2.emailAddress]
    const body = "Hi there. Your code is: 123456"
    await mailslurp.sendEmail(inbox1.id, { to, body })
    // wait for email
    const email = await mailslurp.waitController.waitForLatestEmail(inbox2.id, timeoutMillis, true)
    const pattern = "code is: ([0-9]{6})"
    expect(email.body).toContain("Your code is")
    const result = await mailslurp.emailController.getEmailContentMatch({ pattern }, email.id)
    expect(result.matches).toHaveLength(2);
    expect(result.matches[0]).toEqual("code is: 123456")
    expect(result.matches[1]).toEqual("123456")
    // now do something with the code
})

TIP

You can use MailSlurp in any language using official SDKs or in the online web app (opens new window).

# Matching for email fields

const waitForController = new WaitForControllerApi(config);
const confirmation = await waitForController.waitForMatchingFirstEmail({
    inboxId,
    unreadOnly: true,
    timeout: 30000,
    matchOptions: {
        // pass an array of MatchOption items
        matches: [
            {
                field: MatchOptionFieldEnum.SUBJECT,
                should: MatchOptionShouldEnum.CONTAIN,
                value: "Verification code"
            }
        ]
    }
});
// use a regex in code to extract the content
const r = /.+>(https[^<]+)<\/.+/gs
const results = r.exec(confirmation.body!!)!!;
const url = decodeURIComponent(results[1]);
// now you can use the verification code
expect(url).toBeTruthy();

# Match definitions

Here are the fields and should options that can be used when matching emails:

export enum MatchOptionFieldEnum {
    SUBJECT = 'SUBJECT',
    TO = 'TO',
    BCC = 'BCC',
    CC = 'CC',
    FROM = 'FROM'
}
export enum MatchOptionShouldEnum {
    CONTAIN = 'CONTAIN',
    EQUAL = 'EQUAL'
}

TIP

If you have trouble with matches try asserting the content of the email using the less strict waitForLatestEmail methods.