# Email testing for Playwright Learn how to integrate Mailosaur email testing into Playwright. ## What you'll find in this guide - How to test various aspects of emails - Testing links and codes - Managing email tests ## What you'll need - An understanding of Playwright. - A Mailosaur account. If you don't have one, [start a free trial](/app/signup). - A Playwright project with Mailosaur's API client configured. [See our short guide](/docs/automation/playwright/quickstart) to do this. ## Basic usage To perform email testing with Playwright, simply: 1. Send an email to your Mailosaur inbox (such as a password reset request) 2. Connect to the Mailosaur API with the official client library. 3. Find the email you sent. 4. Perform assertions in the same way as any other test. To learn about Server IDs, and what to replace SERVER_ID with, [see sending test emails to Mailosaur](/docs/email-testing/sending-to-mailosaur). ```js // Setup the API client const mailosaur = new MailosaurClient("API_KEY"); // Search for the message const message = await mailosaur.messages.get('SERVER_ID', { sentTo: 'my-test@SERVER_ID.mailosaur.net' }); // Perform test assertions expect(message.from[0].name).toEqual('Support'); expect(message.from[0].email).toEqual('noreply@acme.com'); ``` You can use this example to search for the email address that a message was sent to. You can also search using the below criteria: | **Parameter** | **Description** | | ------------- | ------------------------------------------------------------- | | sentTo | The full email address to which the target message was sent | | sentFrom | The full email address from which the target message was sent | | subject | Finds messages where the subject line contains this text | | body | Finds messages where the message body contains this text | ### Test email addresses Every inbox in your account (also known as a server) has a unique server ID. This is used to create your inbox domain name, such as: `SERVER_ID.mailosaur.net`. This domain supports a wildcard email pattern, so any email address ending `@SERVER_ID.mailosaur.net` works out of the box. **You don't need to create email addresses** before using them, they just work! However, if you would like extra support creating unique email addresses, you can use this helper method: ```js const emailAddress = mailosaur.servers.generateEmailAddress("SERVER_ID"); console.log(emailAddress); // "bgwqj@SERVER_ID.mailosaur.net" ``` ## Find an email Search for a specific message within your inbox, ideally using `messages.get()`, as it will automatically wait for messages to arrive, and return the full message result. ```js const message = await mailosaur.messages.get("SERVER_ID", { sentTo: "test123@SERVER_ID.mailosaur.net", }); console.log(message.html.body); ``` ### Time range for searching By default searches only look for messages received in the last hour. If you want to look further back than this, just set the 'received after' parameter. ```js // Calculate a datetime for yesterday const yesterday = new Date(Date.now() - 24 * 60 * 60 * 1000); // Use this timestamp in the search const message = await mailosaur.messages.get("SERVER_ID", { sentTo: "test123@SERVER_ID.mailosaur.net", }, { receivedAfter: yesterday }); ``` ### "No matching messages" troubleshooting If you see the error "No matching messages found in time" when searching for messages: - Ensure that the target email or SMS message is visible in the Mailosaur Dashboard, as it may not have arrived at all. - Check when the message arrived. By default, searches only include messages received within the last hour. See "time range for searching" above on how to override this. - Check you have correctly set the **sent to** parameter in your search criteria. ## Other ways to fetch emails > [!WARNING] > > #### Remember, it is usually better to use `messages.get()` > > The `list` and `search` methods only return basic summaries, leaving several properties (including the message body) out. To get this data, use [`.getById()`](#6-messagesgetbyidid). Unless there is a specific reason not to, we recommend using the [`messages.get()`](#2-messagesgetserver-criteria-options) as this automatically waits for a matching result and returns the message in the result. ### List current inbox contents List everything currently in your inbox. ```js // List the most recent messages const result = await mailosaur.messages.list("SERVER_ID"); // Get the most recent message (the first one in the list) const latestMessage = result.items[0]; // Get the full message object const message = await mailosaur.messages.getById(latestMessage.id); console.log(message.html.body); ``` ### Searching for multiple messages See if multiple messages meet a set criteria. ```js // Search for all messages sent to someone@SERVER_ID.mailosaur.net. // Limit results to the first 10 matches only. const result = await mailosaur.messages.search( "SERVER_ID", { sentTo: "someone@SERVER_ID.mailosaur.net", }, { page: 0, itemsPerPage: 10, } ); // Get the most recent message (the first one in the list) const latestMessage = result.items[0]; // Get the full message object const message = await mailosaur.messages.getById(latestMessage.id); console.log(message.html.body); ``` ## Common test scenarios ### Testing basic properties Once you have fetched an email (e.g. using `messages.get`), test the properties of that email: ```js // Test the email subject line expect(message.subject).toEqual("Password reset"); // Test sender information expect(message.from[0].name).toEqual("Support"); expect(message.from[0].email).toEqual("noreply@acme.com"); // Test recipient information expect(message.to[0].name).toEqual("John Smith"); expect(message.to[0].email).toEqual("john@SERVER.mailosaur.net"); ``` #### Testing carbon-copy recipients ```js // Carbon copy (CC) recipients expect(message.cc[0].name).toEqual("Jane Smith"); expect(message.cc[0].email).toEqual("jane@SERVER.mailosaur.net"); // Blind carbon copy (BCC) recipients expect(message.bcc[0].name).toEqual("Jill Smith"); expect(message.bcc[0].email).toEqual("jill@SERVER.mailosaur.net"); ``` ### Testing email contents Most emails have separate HTML and plain text content. This is how to test either content type: #### Plain text content ```js // Check that the email contains some text console.log(message.text.body); // "Hi Jason, ..." ``` #### HTML content When testing HTML content, you can perform basic contains or equals assertions as you would with plain text content: ```js // Check that raw HTML contains some expected content console.log(message.html.body); // "Hello world" ``` ### Testing links Any links that are found in the content of your email are instantly available via the `html.links` or `text.links` arrays, depending on where the link was found: ```js // Working with links in HTML content const linkInHtml = message.html.links[0]; expect(linkInHtml.text).toEqual("Google Search"); expect(linkInHtml.href).toEqual("https://www.google.com/"); // Working with links in plain text content const linkInPlainText = message.text.links[0]; expect(linkInPlainText.href).toEqual("https://www.google.com/"); ``` #### Clicking a link To simulate a link being clicked, you can do this with `HttpClient`: ```js const https = require("https"); // ... const href = message.html.links[0].href; // Make an HTTP call to simulate someone clicking a link https.get(href, (r) => console.log(r.statusCode)); // 200 ``` ### Testing verification codes Codes are automatically extracted from the content and made available via the `html.codes` or `text.codes` arrays: ```js // Working with codes in HTML content const codeInHtml = message.html.codes[0]; expect(codeInHtml.value).toEqual("456812"); // Working with codes in plain text content const codeInText = message.text.codes[0]; expect(codeInText.value).toEqual("456812"); ``` ### Testing attachments Any email attachments are made available via the attachments array: ```js // Number of attachments found console.log(message.attachments.length); // 2 // Get the first attachment const attachment = message.attachments[0]; // Check attachment attributes expect(attachment.fileName).toEqual("example.pdf"); expect(attachment.contentType).toEqual("application/pdf"); expect(attachment.length).toEqual(4028); ``` #### Save an attachment to disk You can download and save attachments using the `files.getAttachment` and `fs` methods: ```js const firstAttachment = message.attachments[0]; const file = await mailosaur.files.getAttachment(firstAttachment.id); fs.writeFileSync(firstAttachment.fileName, file); ``` #### Encoding attachments In some scenarios you may need a base64-encoded copy of an attachment: ```js const firstAttachment = message.attachments[0]; const file = await mailosaur.files.getAttachment(firstAttachment.id); const base64 = file.toString("base64"); console.log(base64); ``` ### Testing images and web beacons Any images found within the HTML content of an email are made available via the `html.images` array: ```js // Number of images found console.log(message.html.images.length); // Get the first image const image = message.html.images[0]; // Check image attributes expect(image.src).toEqual("https://example.com/balloon.png"); expect(image.alt).toEqual("A hot air balloon"); ``` To test an image's online accessibility, or that a [web beacon](https://en.wikipedia.org/wiki/Web_beacon) is working as expected, perform an HTTP request: ```js const https = require("https"); // ... const image = message.html.images[0]; console.log(image.src); // "https://example.com/s.png?abc123" // Make an HTTP call to trigger the web beacon https.get(image.src, (r) => console.log(r.statusCode)); // 200 ``` ### Sending an email If your product is set up to accept inbound emails, you can use the Mailosaur sending feature to trigger this functionality. The `messages.create` command creates and sends an email to a verified external email address: ```js await mailosaur.messages.create("SERVER_ID", { to: "verified-address@example.com", send: true, subject: "Request", text: "Please can you give us a call back?", }); ``` The options available to use with this method are: | Parameter | Description | | ----------- | ------------------------------------------------------------------------------------ | | send | This must be set to true if you are sending an outbound email | | to | The email address to which the email will be sent. Must be a verified email address. | | subject | The email subject line | | text | The plain text body of the email. | | html | The HTML body of the email. | | attachments | Optional attachments (see 'include attachments' below) | #### Include attachments You can include attachments in emails sent via the API, by including an array of base64-encoded attachment objects: ```js const attachments = [ { fileName: "cat.png", contentType: "image/png", content: "{BASE64_ENCODED_FILE}", }, ]; await mailosaur.messages.create("SERVER_ID", { to: "verified-address@example.com", send: true, subject: "Email from Mailosaur", html: "
Hello world.
", attachments: attachments, }); ``` ### Replying to an email If your product handles email replies, the Mailosaur reply feature simulates this. When you reply, the message is sent back to the original account: ```js await mailosaur.messages.reply("MESSAGE_ID", { text: "FYI", }); ``` | Parameter | Description | | ----------- | ------------------------------------------------------ | | text | Any additional text content to include in the reply | | html | Any additional HTML content to include in the reply | | subject | Optionally override the default subject line | | attachments | Optional attachments (see 'include attachments' above) | ### Forwarding a message to email You can forward messages from your Mailosaur account to external email addresses either one-by-one, or via the creation of automated forwarding rules. To do this **it is essential to set up a [verified external email address](/docs/managing-your-account/external-email-addresses)**, so you can send email to it: ```js await mailosaur.messages.forward("MESSAGE_ID", { to: "verified-address@example.com", text: "FYI", }); ``` | Parameter | Description | | --------- | ------------------------------------------------------------------------------------- | | to | The email address to which the message will be sent. Must be a verified email address | | text | Any additional text content to forward the message with | | html | Any additional HTML content to forward the message with | | subject | Optionally override the default subject line | ## Deleting messages ### Deleting an individual message Permanently deletes a single message and any attachments related to the message. This cannot be undone: ```js await mailosaur.messages.del("MESSAGE_ID"); ``` ### Delete all messages Permanently deletes all messages held in the specified inbox and any attachments related to each message. This cannot be undone: ```js await mailosaur.messages.deleteAll("SERVER_ID"); ``` ## See also - [SMS testing guide](/docs/automation/playwright/sms-testing) - [MFA/2FA guide](/docs/authenticator)