# Mailosaur > Mailosaur is an email and SMS testing platform. It gives teams instant, secure test inboxes and phone numbers, and email previews across clients and devices, to test every sign-up, password reset and authentication flow automatically. --- Source: https://mailosaur.com/docs/api # Email and SMS Testing API Using the Mailosaur API, you can write automated tests for the email and SMS messages your product sends. ## Overview The Mailosaur API lets you test email using a simple REST API. You can make the API calls yourself, however because email and SMS messages can take time to arrive, we highly recommend using one of our official clients.   ## Authentication The Mailosaur API uses [API keys](/docs/managing-your-account/api-keys) to authenticate requests. Authentication to the API is performed via **HTTP Basic Auth**. Your API key must be provided as the basic auth username value. You do not need to provide a password. Your API keys carry many privileges, so always keep them secret and secure! Never share your API key in publicly-accessible areas such GitHub, client-side code, etc. All API requests must be made over HTTPS. Calls made over plain HTTP will fail. API requests without authentication will also fail. ```curl curl https://mailosaur.com/api/servers \ -u api:YOUR_API_KEY ``` ### Managing API keys You can [manage all your API keys](/docs/managing-your-account/api-keys) in the Mailosaur Dashboard. ## Errors ### HTTP Status Codes Mailosaur uses conventional HTTP response codes to indicate the success or failure of an API request. In general, codes in the ```2xx``` range indicate success, codes in the ```4xx``` range indicate an error that failed given the information provided (e.g., a required parameter was omitted), and codes in the ```5xx``` range indicate an error with Mailosaur’s servers (give us a shout in the unlikely event that you see one of those). | CODE | DESCRIPTION | | ------ | ------ | | **200 OK** | Request was successful. | | **204 No Content** | Request was successful, no response content. | | **400 Bad Request** | The request could not be handled, often due to missing a required parameter. | | **401 Unauthorized** | No valid API key provided. | | **404 Not Found** | The requested resource doesn’t exist. | | **5XX Server Errors** | Something went wrong at Mailosaur. (Give us a shout). | ### Error handling In case of an error the server will return as much information as possible. In the case of a ```401``` or ```404``` error the status code gives as much information as you’d need. But for ```400``` errors Mailosaur will return a JSON object containing the structure below. Note that our [client libraries](/docs/automation) convert responses to appropriate language-specific objects. | FIELD | DESCRIPTION | | ------- | ------- | | **type** | The type of error returned. | | **message** | A human-readable message providing more details about the error. | | **parameters** | A JSON object containing a key for each property name at fault, with a human-readable message per field. | | **model** | The request model that was sent and failed to be processed. | ## Email and SMS Testing The Messages API allows you to list, search, view, modify and create email and SMS messages within your Mailosaur account. ### Retrieve a message `GET /api/messages/:id` If you are using one of [Mailosaur’s client libraries](/docs/automation), we **highly recommend** using the ```.Get``` method instead of ```.GetById```, as it automatically waits for results to arrive! Retrieves the detail for a single message. Simply supply the unique identifier for the required message. To get the ID of a message you need to call one of our other API calls which returns a list of messages. Each message in the list will contain an ID which you can use to make this call. #### Parameters | Name | Type | Location | Required | Description | | --- | --- | --- | --- | --- | | id | string | path | Yes | The identifier of the message to be retrieved. This can be found via other API calls such as List/Search. | #### Request ```curl curl \ -u api:YOUR_API_KEY \ https://mailosaur.com/api/messages/MESSAGE_ID ``` ```nodejs const message = await mailosaur.messages.getById('MESSAGE_ID'); ``` ```cypress cy.mailosaurGetMessageById('MESSAGE_ID') .then(message => { cy.log(message.subject); // "Example" }); ``` ```python message = mailosaur.messages.get_by_id("MESSAGE_ID") ``` ```java Message message = mailosaur.messages().getById("MESSAGE_ID"); ``` ```dotnet var message = mailosaur.Messages.GetById("MESSAGE_ID"); ``` ```ruby message = mailosaur.messages.get_by_id('MESSAGE_ID') ``` ```php $message = $mailosaur->messages->getById('MESSAGE_ID'); ``` ```go $message = $mailosaur->messages->getById('MESSAGE_ID'); ``` #### Response ```json { "id": "77061c9f-da47-4009-9f33-9715a3bbf00c", "received": "2019-08-06T17:44:07.197781+00:00", "type": "Email", "subject": "Email subject line", "from": [{ "name": "Acme", "email": "noreply@example.com" }], "to": [{ "name": "Jane Doe", "email": "janedoe@abc1234.mailosaur.net" }], "cc": [], "bcc": [], "html": { "links": [{ "href": "https://example.com/signup", "text": "Sign Up Now" }], "images": [], "body": "Lorem ipsum..." }, "text": { "links": [{ "href": "https://example.com/signup", "text": "https://example.com/signup" }], "body": "Lorem ipsum..." }, "attachments": [], "metadata": { "headers": [{ "field": "MIME-Version", "value": "1.0" }] }, "server": "abcd1234" } ``` ### Delete a message `DELETE /api/messages/:id` Permanently deletes a message. This operation cannot be undone. Also deletes any attachments related to the message. #### Parameters | Name | Type | Location | Required | Description | | --- | --- | --- | --- | --- | | id | string | path | Yes | The identifier of the message to be deleted. | #### Request ```curl curl \ -X DELETE \ -u api:YOUR_API_KEY \ https://mailosaur.com/api/messages/MESSAGE_ID ``` ```nodejs await mailosaur.messages.del('MESSAGE_ID'); ``` ```cypress cy.mailosaurDeleteMessage('MESSAGE_ID'); ``` ```python mailosaur.messages.delete("MESSAGE_ID") ``` ```java mailosaur.messages().delete("MESSAGE_ID"); ``` ```dotnet mailosaur.Messages.Delete("MESSAGE_ID"); ``` ```ruby mailosaur.messages.delete('MESSAGE_ID') ``` ```php $mailosaur->messages->delete('MESSAGE_ID'); ``` ```go m.Messages.Delete("MESSAGE_ID") ``` ### List all messages `GET /api/messages?server=:server` Returns a list of your messages in summary form. The summaries are returned sorted by received date, with the most recently-received messages appearing first. #### Parameters | Name | Type | Location | Required | Description | | --- | --- | --- | --- | --- | | server | string | query | Yes | The identifier of the server hosting the messages. | | receivedAfter | date/time | query | No | Limits results to only messages received after this date/time. | | page | integer | query | No | Used in conjunction with `itemsPerPage` to support pagination. | | itemsPerPage | integer | query | No | A limit on the number of results to be returned per page. Can be set between 1 and 1000 items, the default is 50. | | dir | string | query | No | Optionally limits results based on the direction (`Sent` or `Received`), with the default being `Received`. | #### Request ```curl curl \ -u api:YOUR_API_KEY \ https://mailosaur.com/api/messages?server=SERVER_ID ``` ```nodejs const result = await mailosaur.messages.list('SERVER_ID'); console.log(result.items[0].subject); // "Example" ``` ```cypress cy.mailosaurListMessages('SERVER_ID').then(result => { cy.log(result.items[0].subject); // "Example" }); ``` ```python result = mailosaur.messages.list("SERVER_ID") print result.items[0].subject # "Example" ``` ```java MessageListParams params = new MessageListParams(); params.withServer("SERVER_ID"); MessageListResult result = mailosaur.messages().list(params); ``` ```dotnet var result = mailosaur.Messages.List("SERVER_ID"); Console.WriteLine(result.Items[0].Subject); // "Example" ``` ```ruby result = mailosaur.messages.list('SERVER_ID') print(result.items[0].subject) # "Example" ``` ```php $result = $mailosaur->messages->all('SERVER_ID'); print($result->items[0]->subject); // "Example" ``` ```go result := m.Messages.List("SERVER_ID") fmt.Println(result.Items[0].Subject) // "Example" ``` #### Response ```json [ { "id": "77061c9f-da47-4009-9f33-9715a3bbf00c", "received": "2019-08-06T17:44:07.197781+00:00", "type": "Email", "subject": "Email subject line", "from": [{ "name": "Acme", "email": "noreply@example.com" }], "to": [{ "name": "Jane Doe", "email": "janedoe@abc1234.mailosaur.net" }], "cc": [], "bcc": [] } ] ``` ### Delete all messages `DELETE /api/messages?server=:server` Permanently deletes all messages held by the specified server. This operation cannot be undone. Also deletes any attachments related to each message. #### Parameters | Name | Type | Location | Required | Description | | --- | --- | --- | --- | --- | | server | string | query | Yes | The identifier of the server to be emptied. | #### Request ```curl curl \ -X DELETE \ -u api:YOUR_API_KEY \ https://mailosaur.com/api/messages?server=SERVER_ID ``` ```nodejs await mailosaur.messages.deleteAll('SERVER_ID'); ``` ```cypress cy.mailosaurDeleteAllMessages('SERVER_ID'); ``` ```python mailosaur.messages.delete_all("SERVER_ID") ``` ```java mailosaur.messages().deleteAll("SERVER_ID"); ``` ```dotnet mailosaur.Messages.DeleteAll("SERVER_ID"); ``` ```ruby mailosaur.messages.delete_all('SERVER_ID') ``` ```php $mailosaur->messages->deleteAll('SERVER_ID'); ``` ```go m.Messages.DeleteAll("SERVER_ID") ``` ### Search for messages `POST /api/messages/search?server=:server` If you are using one of [Mailosaur’s client libraries](/docs/automation), we **highly recommend** using the ```.Get``` method instead of ```.Search```, as it automatically waits for results to arrive. It also returns the whole email/SMS, rather than just a message summary. Returns a list of message summaries matching the specified search criteria, in summary form. The summaries are returned sorted by received date, with the most recently-received messages appearing first. To get the full message content, including HTML & Text body content, you need to use the Retrieve a message endpoint. Alternatively you can search and retrieve in a single call by using our official client libraries. #### Parameters | Name | Type | Location | Required | Description | | --- | --- | --- | --- | --- | | server | string | query | Yes | The identifier of the server hosting the messages. | | receivedAfter | date/time | query | No | Limits results to only messages received after this date/time. | | page | integer | query | No | Used in conjunction with `itemsPerPage` to support pagination. | | itemsPerPage | integer | query | No | A limit on the number of results to be returned per page. Can be set between 1 and 1000 items, the default is 50. | | dir | string | query | No | Optionally limits results based on the direction (`Sent` or `Received`), with the default being `Received`. | | sentFrom | string | body | No | The full email address or phone number from which the target message was sent. | | sentTo | string | body | No | The full email address or phone number to which the target message was sent. | | subject | string | body | No | The value to seek within the target email’s subject line. | | body | string | body | No | The value to seek within the target message’s HTML or text body. | | match | string | body | No | If set to `ALL` (default), then only results that match all specified criteria will be returned. If set to `ANY`, results that match any of the specified criteria will be returned. | #### Request ```curl curl \ -X POST \ -H 'Content-Type: application/json' \ -d '{"sentTo":"someone@SERVER_ID.mailosaur.net"}' \ -u api:YOUR_API_KEY \ https://mailosaur.com/api/messages/search?server=SERVER_ID ``` ```nodejs const result = await mailosaur.messages.search('SERVER_ID', { sentTo: 'someone@SERVER_ID.mailosaur.net' }); // Get the most recent match const message = result.items[0]; console.log('Subject:', message.subject); ``` ```cypress cy.mailosaurSearchMessages('SERVER_ID', { sentTo: 'someone@SERVER_ID.mailosaur.net' }).then(result => { // Get the most recent match const message = result.items[0]; cy.log(`Subject: ${message.subject}`); }); ``` ```python from mailosaur.models import SearchCriteria # ... criteria = SearchCriteria() criteria.sent_to = "someone@SERVER_ID.mailosaur.net" result = mailosaur.messages.search('SERVER_ID', criteria) # Get the most recent match message = result.items[0] print('Subject: ' + message.subject) ``` ```java MessageSearchParams params = new MessageSearchParams(); params.withServer("SERVER_ID"); SearchCriteria criteria = new SearchCriteria(); criteria.withSentTo("someone@SERVER_ID.mailosaur.net"); MessageListResult result = mailosaur.messages().search(params, criteria); // Get the most recent match MessageSummary message = result.items().get(0); System.out.println("Subject: " + message.subject()); ``` ```dotnet var result = mailosaur.Messages.Search("SERVER_ID", new SearchCriteria() { SentTo = "someone@SERVER_ID.mailosaur.net" }); // Get the most recent match var message = result.Items[0]; Console.WriteLine("Subject: " + message.Subject); ``` ```ruby criteria = Mailosaur::Models::SearchCriteria.new() criteria.sent_to = "someone@SERVER_ID.mailosaur.net" result = mailosaur.messages.search("SERVER_ID", criteria) # Get the most recent match message = result.items[0] print('Subject: ' + message.subject) ``` ```php $criteria = new SearchCriteria(); $criteria->sentTo = 'someone@SERVER_ID.mailosaur.net'; $result = $mailosaur->messages->search('SERVER_ID', $criteria); # Get the most recent match $message = $result->items[0]; print('Subject: ' . $message->subject); ``` ```go params := &mailosaur.MessageListParams { Server: server, } criteria := &mailosaur.SearchCriteria { SentTo: "someone@SERVER_ID.mailosaur.net", } result, err := m.Messages.Search(params, criteria) if (err != nil) { // Handle err } // Get the most recent match message := result.Items[0] fmt.Println("Subject: " + message.Subject) ``` #### Response ```json [ { "id": "77061c9f-da47-4009-9f33-9715a3bbf00c", "received": "2019-08-06T17:44:07.197781+00:00", "type": "Email", "subject": "Email subject line", "from": [{ "name": "Acme", "email": "noreply@example.com" }], "to": [{ "name": "Jane Doe", "email": "janedoe@abc1234.mailosaur.net" }], "cc": [], "bcc": [] } ] ``` ### Forward a message `POST /api/messages/:id/forward` Forward an email or SMS message to a [verified external email address](/docs/managing-your-account/external-email-addresses). Supply the unique identifier for message you want to forward, as well as additional, relevant options. To get the ID of a message you need to call one of our other API calls which returns a list of messages. Each message in the list will contain an ID which you can use to make this call. #### Parameters | Name | Type | Location | Required | Description | | --- | --- | --- | --- | --- | | id | string | path | Yes | The identifier of the message to be forwarded. This can be found via other API calls such as Search for messages. | | to | string | body | Yes | The verified external email address to which the message should be sent. | | subject | string | body | No | Optionally override an email's subject line. | | html | string | body | No | Any HTML content to prefix the forwarded message with. | | text | string | body | No | Any plain text content to prefix the forwarded message with. | #### Request ```curl curl \ -X POST \ -H 'Content-Type: application/json' \ -d '{"to":"someone@example.com","text":"Example"}' \ -u api:YOUR_API_KEY \ https://mailosaur.com/api/messages/MESSAGE_ID/forward ``` ```nodejs // MESSAGE_ID: The `id` of the message you want to forward await mailosaur.messages.forward('MESSAGE_ID', { to: 'someone@example.com', // must be a verified address html: '
Hello world.
' }); ``` ```cypress // MESSAGE_ID: The `id` of the message you want to reply to cy.mailosaurForwardMessage('MESSAGE_ID', { to: 'someone@example.com', // must be a verified address html: 'Hello world.
' }) ``` ```python recipient = "someone@example.com" # must be a verified address body = "Hello world.
" options = MessageForwardOptions(recipient, html=body) # MESSAGE_ID: The `id` of the message you want to forward mailosaur.messages.forward("MESSAGE_ID", options) ``` ```java MessageForwardOptions options = new MessageForwardOptions(); options.withTo("someone@example.com") // must be a verified address .withHtml("Hello world.
"); // MESSAGE_ID: The `id` of the message you want to forward mailosaur.messages().forward("MESSAGE_ID", options); ``` ```dotnet // MESSAGE_ID: The `id` of the message you want to forward mailosaur.Messages.Forward("MESSAGE_ID", new MessageForwardOptions() { To = "someone@example.com", // must be a verified address Html = "Hello world.
" } ); ``` ```ruby options = Mailosaur::Models::MessageForwardOptions.new() options.to = 'someone@example.com' # must be a verified address options.html = 'Hello world.
' # MESSAGE_ID: The `id` of the message you want to forward mailosaur.messages.forward('MESSAGE_ID', options) ``` ```php $options = new MessageForwardOptions(); $options->to = 'someone@example.com'; // must be a verified address $options->html = 'Hello world.
'; // MESSAGE_ID: The `id` of the message you want to forward $mailosaur->messages->forward('MESSAGE_ID', $options); ``` ```go // MESSAGE_ID: The `id` of the message you want to forward m.Messages.Forward("MESSAGE_ID", &MessageForwardOptions{ To: "someone@example.com", // must be a verified address Html: "Hello world.
", }) ``` #### Response ```json { "id": "77061c9f-da47-4009-9f33-9715a3bbf00c", "received": "2019-08-06T17:44:07.197781+00:00", "type": "Email", "subject": "Email subject line", "from": [{ "name": "Acme", "email": "noreply@example.com" }], "to": [{ "name": "Jane Doe", "email": "janedoe@abc1234.mailosaur.net" }], "cc": [], "bcc": [], "html": { "links": [{ "href": "https://example.com/signup", "text": "Sign Up Now" }], "images": [], "body": "Lorem ipsum..." }, "text": { "links": [{ "href": "https://example.com/signup", "text": "https://example.com/signup" }], "body": "Lorem ipsum..." }, "attachments": [], "metadata": { "headers": [{ "field": "MIME-Version", "value": "1.0" }] }, "server": "abcd1234" } ``` ### Reply to a message `POST /api/messages/:id/reply` Reply to an email or SMS message. Supply the unique identifier for message you want to forward, as well as additional, relevant options. Email replies can only be sent back to [verified external email address](/docs/managing-your-account/external-email-addresses). SMS replies can only contain [approved phrases](/docs/sms-testing/replying#0-approved-phrases) to prevent fraud. To get the ID of a message you need to call one of our other API calls which returns a list of messages. Each message in the list will contain an ID which you can use to make this call. #### Parameters | Name | Type | Location | Required | Description | | --- | --- | --- | --- | --- | | id | string | path | Yes | The identifier of the message to be replied to. This can be found via other API calls such as Search for messages. | | subject | string | body | No | Optionally override an email's subject line. | | html | string | body | No | Any HTML content to prefix the reply with. | | text | string | body | No | Any plain text content to prefix the reply with. | | attachments | array | body | No | An object array of base64-encoded attachment objects (`fileName`, `contentType`, `content`). | #### Request ```curl curl \ -X POST \ -H 'Content-Type: application/json' \ -d '{"text":"Example"}' \ -u api:YOUR_API_KEY \ https://mailosaur.com/api/messages/MESSAGE_ID/reply ``` ```nodejs // MESSAGE_ID: The `id` of the message you want to reply to await mailosaur.messages.reply('MESSAGE_ID', { html: 'Hello world.
' }); ``` ```cypress // MESSAGE_ID: The `id` of the message you want to reply to cy.mailosaurReplyToMessage('MESSAGE_ID', { html: 'Hello world.
' }); ``` ```python body = "Hello world.
" options = MessageReplyOptions(html=body) # MESSAGE_ID: The `id` of the message you want to reply to mailosaur.messages.reply("MESSAGE_ID", options) ``` ```java MessageReplyOptions options = new MessageReplyOptions(); options.withHtml("Hello world.
"); // MESSAGE_ID: The `id` of the message you want to reply to mailosaur.messages().reply("MESSAGE_ID", options); ``` ```dotnet // MESSAGE_ID: The `id` of the message you want to reply to mailosaur.Messages.Reply("MESSAGE_ID", new MessageReplyOptions() { Html = "Hello world.
" } ); ``` ```ruby options = Mailosaur::Models::MessageReplyOptions.new() options.html = 'Hello world.
' # MESSAGE_ID: The `id` of the message you want to reply to mailosaur.messages.reply('MESSAGE_ID', options) ``` ```php $options = new MessageReplyOptions(); $options->html = 'Hello world.
'; // MESSAGE_ID: The `id` of the message you want to reply to $mailosaur->messages->reply('MESSAGE_ID', $options); ``` ```go // MESSAGE_ID: The `id` of the message you want to reply to m.Messages.Reply("MESSAGE_ID", &MessageReplyOptions{ Html: "Hello world.
", }) ``` #### Response ```json { "id": "77061c9f-da47-4009-9f33-9715a3bbf00c", "received": "2019-08-06T17:44:07.197781+00:00", "type": "Email", "subject": "Email subject line", "from": [{ "name": "Acme", "email": "noreply@example.com" }], "to": [{ "name": "Jane Doe", "email": "janedoe@abc1234.mailosaur.net" }], "cc": [], "bcc": [], "html": { "links": [{ "href": "https://example.com/signup", "text": "Sign Up Now" }], "images": [], "body": "Lorem ipsum..." }, "text": { "links": [{ "href": "https://example.com/signup", "text": "https://example.com/signup" }], "body": "Lorem ipsum..." }, "attachments": [], "metadata": { "headers": [{ "field": "MIME-Version", "value": "1.0" }] }, "server": "abcd1234" } ``` ### Send an email `POST /api/messages?server=:server` You can only send emails to [verified external email address](/docs/managing-your-account/external-email-addresses). Supply the unique identifier for server you want to send from, as well as additional, relevant options. #### Parameters | Name | Type | Location | Required | Description | | --- | --- | --- | --- | --- | | server | string | query | Yes | The identifier of the server from which the email should be sent. | | to | string | body | Yes | The verified external email address to which the email should be sent. | | from | string | body | No | Optionally overrides of the message’s ‘from’ address. This **must** be an address ending with `YOUR_SERVER.mailosaur.net`, such as `my-emails @a1bcdef2.mailosaur.net`. | | subject | string | body | Yes | The subject line for an email. | | html | string | body | No | HTML content for the email. | | text | string | body | No | Plain text content for the email. | | send | boolean | body | No | If not `true`, then the email will be created in your server, but will not be sent. | | attachments | array | body | No | An object array of base64-encoded attachment objects (`fileName`, `contentType`, `content`). | #### Request ```curl curl \ -X POST \ -H 'Content-Type: application/json' \ -d '{"to":"someone@example.com","subject":"Email from Mailosaur","text":"Example","send":true}' \ -u api:YOUR_API_KEY \ https://mailosaur.com/api/messages?server=SERVER_ID ``` ```nodejs await mailosaur.messages.create('SERVER_ID', { to: 'someone@example.com', // must be a verified address subject: 'Email from Mailosaur', html: 'Hello world.
', send: true }); ``` ```cypress cy.mailosaurCreateMessage('SERVER_ID', { to: 'someone@example.com', // must be a verified address subject: 'Email from Mailosaur', html: 'Hello world.
', send: true }); ``` ```python recipient = "someone@example.com" # must be a verified address subject = "Email from Mailosaur" body = "Hello world.
" options = MessageCreateOptions( recipient, True, subject, html=body) mailosaur.messages.create("SERVER_ID", options) ``` ```java MessageCreateOptions options = new MessageCreateOptions(); options.withTo("someone@example.com") // must be a verified address .withSubject("Email from Mailosaur") .withHtml("Hello world.
") .withSend(true); mailosaur.messages().create("SERVER_ID", options); ``` ```dotnet mailosaur.Messages.Create("SERVER_ID", new MessageCreateOptions() { To = "someone@example.com", // must be a verified address Subject = "Email from Mailosaur", Html = "Hello world.
", Send = true } ); ``` ```ruby options = Mailosaur::Models::MessageCreateOptions.new() options.to = 'someone@example.com' # must be a verified address options.subject = 'Email from Mailosaur' options.html = 'Hello world.
' options.send = true mailosaur.messages.create('SERVER_ID', options) ``` ```php $options = new MessageCreateOptions(); $options->to = 'someone@example.com'; // must be a verified address $options->subject = 'Email from Mailosaur'; $options->html = 'Hello world.
'; $options->send = TRUE; $mailosaur->messages->create('SERVER_ID', $options); ``` ```go m.Messages.Create("SERVER_ID", &MessageCreateOptions{ To: "someone@example.com", // must be a verified address Subject: "Email from Mailosaur", Html: "Hello world.
", Send: true, }) ``` #### Response ```json { "id": "77061c9f-da47-4009-9f33-9715a3bbf00c", "received": "2019-08-06T17:44:07.197781+00:00", "type": "Email", "subject": "Email subject line", "from": [{ "name": "Acme", "email": "noreply@example.com" }], "to": [{ "name": "Jane Doe", "email": "janedoe@abc1234.mailosaur.net" }], "cc": [], "bcc": [], "html": { "links": [{ "href": "https://example.com/signup", "text": "Sign Up Now" }], "images": [], "body": "Lorem ipsum..." }, "text": { "links": [{ "href": "https://example.com/signup", "text": "https://example.com/signup" }], "body": "Lorem ipsum..." }, "attachments": [], "metadata": { "headers": [{ "field": "MIME-Version", "value": "1.0" }] }, "server": "abcd1234" } ``` ## Authenticator (2FA) The Authenticator (2FA devices) API allows you to generate one-time passwords (OTPs) and virtual security devices, for the purpose of testing authentication systems. ### Retrieve one-time password `POST /api/devices/otp` Retrieves the one-time password for a given base32-encoded secret. #### Parameters | Name | Type | Location | Required | Description | | --- | --- | --- | --- | --- | | sharedSecret | string | body | Yes | The base32-encoded shared secret to generate a one-time password for. | #### Request ```curl curl \ -X POST \ -H 'Content-Type: application/json' \ -d '{"sharedSecret":"ONSWG4TFOQYTEMY="}' \ -u api:YOUR_API_KEY \ https://mailosaur.com/api/devices/otp ``` ```nodejs const sharedSecret = 'ONSWG4TFOQYTEMY='; const currentOtp = await mailosaur.devices.otp(sharedSecret); console.log(currentOtp.code); // "564214" ``` ```cypress const sharedSecret = 'ONSWG4TFOQYTEMY='; cy.mailosaurGetDeviceOtp(sharedSecret) .then(currentOtp => { cy.log(currentOtp.code); // "564214" }); ``` ```python shared_secret = "ONSWG4TFOQYTEMY=" current_otp = mailosaur.devices.otp(shared_secret) print current_otp.code # "564214" ``` ```java String sharedSecret = "ONSWG4TFOQYTEMY="; String currentOtp = mailosaur.devices().otp(sharedSecret); System.out.println(currentOtp.code); // "564214" ``` ```dotnet var sharedSecret = "ONSWG4TFOQYTEMY="; var currentOtp = mailosaur.Devices.Otp(sharedSecret); Console.WriteLine(currentOtp.code); // "564214" ``` ```ruby shared_secret = 'ONSWG4TFOQYTEMY=' current_otp = mailosaur.devices.otp(shared_secret) print(current_otp.code) # "564214" ``` ```php $sharedSecret = 'ONSWG4TFOQYTEMY='; $currentOtp = $mailosaur->devices->otp($sharedSecret); print($currentOtp->code); // "564214" ``` ```go sharedSecret := "ONSWG4TFOQYTEMY=" currentOtp := m.Devices.Otp(sharedSecret) fmt.Println(currentOtp.Code) // "564214" ``` #### Response ```json { "code": "123456", "expires": "2022-01-01T00:00:00Z" } ``` ### List all devices `GET /api/devices` Returns a list of your virtual security devices. #### Request ```curl curl \ -u api:YOUR_API_KEY \ https://mailosaur.com/api/devices ``` ```nodejs const result = await mailosaur.devices.list(); console.log(result.items[0].name); // "Example" ``` ```cypress cy.mailosaurListDevices().then(result => { cy.log(result.items[0].name); // "Example" }); ``` ```python result = mailosaur.devices.list() print result.items[0].name # "Example" ``` ```java DeviceListResult result = mailosaur.devices().list(); ``` ```dotnet var result = mailosaur.Devices.List(); Console.WriteLine(result.Items[0].Name); // "Example" ``` ```ruby result = mailosaur.devices.list() print(result.items[0].name) # "Example" ``` ```php $result = $mailosaur->devices->all(); print($result->items[0]->name); // "Example" ``` ```go result := m.Devices.List() fmt.Println(result.Items[0].Name) // "Example" ``` #### Response ```json [ { "id": "abcd1234", "name": "Device name" } ] ``` ### Create a device `POST /api/devices` Creates a new virtual security device and returns it. #### Parameters | Name | Type | Location | Required | Description | | --- | --- | --- | --- | --- | | name | string | body | Yes | A name for the virtual device. | | sharedSecret | string | body | Yes | The base32-encoded shared secret to generate a one-time password for. | #### Request ```curl curl \ -X POST \ -H 'Content-Type: application/json' \ -d '{"name":"Example","sharedSecret":"ONSWG4TFOQYTEMY="}' \ -u api:YOUR_API_KEY \ https://mailosaur.com/api/devices ``` ```nodejs await mailosaur.devices.create({ name: 'Example', sharedSecret: 'ONSWG4TFOQYTEMY=' }); ``` ```cypress cy.mailosaurCreateDevice({ name: 'Example', sharedSecret: 'ONSWG4TFOQYTEMY=' }); ``` ```python name = "Example" shared_secret = "ONSWG4TFOQYTEMY=" options = DeviceCreateOptions(name, shared_secret) mailosaur.devices.create(options) ``` ```java DeviceCreateOptions options = new DeviceCreateOptions(); options.withName("Example") .withSharedSecret("ONSWG4TFOQYTEMY="); mailosaur.devices().create(options); ``` ```dotnet mailosaur.Devices.Create(new DeviceCreateOptions() { Name = "Example", SharedSecret = "ONSWG4TFOQYTEMY=" } ); ``` ```ruby options = Mailosaur::Models::DeviceCreateOptions.new() options.name = 'Example' options.shared_secret = 'ONSWG4TFOQYTEMY=' mailosaur.devices.create(options) ``` ```php $options = new DeviceCreateOptions(); $options->name = 'Example'; $options->sharedSecret = 'ONSWG4TFOQYTEMY='; $mailosaur->devices->create($options); ``` ```go m.Devices.Create(&DeviceCreateOptions{ Name: "Example", SharedSecret: "ONSWG4TFOQYTEMY=", }) ``` #### Response ```json { "id": "abcd1234", "name": "My device" } ``` ### Retrieve OTP for an existing device `GET /api/devices/:id/otp` Retrieves the current one-time password for an existing virtual security device. Simply supply the unique identifier for the required device. #### Parameters | Name | Type | Location | Required | Description | | --- | --- | --- | --- | --- | | id | string | path | Yes | The identifier of the device to be retrieved. | #### Request ```curl curl \ -u api:YOUR_API_KEY \ https://mailosaur.com/api/devices/DEVICE_ID/otp ``` ```nodejs const currentOtp = await mailosaur.devices.otp('DEVICE_ID'); console.log(currentOtp.code); // "564214" ``` ```cypress cy.mailosaurGetDeviceOtp('DEVICE_ID') .then(currentOtp => { cy.log(currentOtp.code); // "564214" }); ``` ```python current_otp = mailosaur.devices.otp("DEVICE_ID") print current_otp.code # "564214" ``` ```java String currentOtp = mailosaur.devices().otp("DEVICE_ID"); System.out.println(currentOtp.code); // "564214" ``` ```dotnet var currentOtp = mailosaur.Devices.Otp("DEVICE_ID"); Console.WriteLine(currentOtp.code); // "564214" ``` ```ruby current_otp = mailosaur.devices.otp('DEVICE_ID') print(current_otp.code) # "564214" ``` ```php $currentOtp = $mailosaur->devices->otp('DEVICE_ID'); print($currentOtp->code); // "564214" ``` ```go currentOtp := m.Devices.Otp("DEVICE_ID") fmt.Println(currentOtp.Code) // "564214" ``` #### Response ```json { "code": "123456", "expires": "2022-01-01T00:00:00Z" } ``` ### Delete a device `DELETE /api/devices/:id` Permanently deletes a device. This operation cannot be undone. #### Parameters | Name | Type | Location | Required | Description | | --- | --- | --- | --- | --- | | id | string | path | Yes | The identifier of the device to be deleted. | #### Request ```curl curl \ -X DELETE \ -u api:YOUR_API_KEY \ https://mailosaur.com/api/devices/DEVICE_ID ``` ```nodejs await mailosaur.devices.del('DEVICE_ID'); ``` ```cypress cy.mailosaurDeleteDevice('DEVICE_ID'); ``` ```python mailosaur.devices.delete("DEVICE_ID") ``` ```java mailosaur.devices().delete("DEVICE_ID"); ``` ```dotnet mailosaur.Devices.Delete("DEVICE_ID"); ``` ```ruby mailosaur.devices.delete('DELETE_ID') ``` ```php $mailosaur->devices->delete('DEVICE_ID'); ``` ```go m.Devices.Delete("DEVICE_ID") ``` ## Files The Files API allows you to download files, such as message attachments, from Mailosaur. ### Download an attachment `GET /api/files/attachments/:id` Downloads a single attachment. Simply supply the unique identifier for the required attachment. #### Parameters | Name | Type | Location | Required | Description | | --- | --- | --- | --- | --- | | id | string | path | Yes | The identifier of the attachment to be downloaded. | #### Request ```curl curl \ -o example.png \ -u api:YOUR_API_KEY \ https://mailosaur.com/api/files/attachments/ATTACHMENT_ID ``` ```nodejs const fs = require('fs'); // ... const file = await mailosaur.files.getAttachment('ATTACHMENT_ID'); fs.writeFileSync('example.png', file); ``` ```cypress cy.mailosaurDownloadAttachment('ATTACHMENT_ID').then(file => { cy.writeFile('example.png', file, 'binary') }) ``` ```python file = mailosaur.files.get_attachment('ATTACHMENT_ID').content f = open('example.png', 'wb') f.write(file) f.close() ``` ```java byte[] file = mailosaur.files().getAttachment("ATTACHMENT_ID"); Files.write(Paths.get("example.png"), file); ``` ```dotnet var file = mailosaur.Files.GetAttachment("ATTACHMENT_ID"); File.WriteAllBytes("example.png", file); ``` ```ruby file = mailosaur.files.get_attachment('ATTACHMENT_ID') File.open(first_attachment.file_name, 'wb') { |fp| fp.write(file) } ``` ```php $file = $mailosaur->files->getAttachment("ATTACHMENT_ID"); $f = fopen("example.png", "w") or die("Unable to open file!"); fwrite($f, $file); fclose($f); ``` ```go var file, _ = m.Files.GetAttachment("ATTACHMENT_ID") var err = os.WriteFile("example.png", file, 0644) if err != nil { // handle error } ``` ### Download EML `GET /api/files/email/:id` Downloads an EML file representing the specified email. Simply supply the unique identifier for the required email. #### Parameters | Name | Type | Location | Required | Description | | --- | --- | --- | --- | --- | | id | string | path | Yes | The identifier of the email to be downloaded. | #### Request ```curl curl \ -o example.eml \ -u api:YOUR_API_KEY \ https://mailosaur.com/api/files/email/MESSAGE_ID ``` ```nodejs const fs = require('fs'); // ... const file = await mailosaur.files.getEmail('MESSAGE_ID'); fs.writeFileSync('example.eml', file); ``` ```cypress cy.mailosaurDownloadMessage('MESSAGE_ID').then(file => { cy.writeFile('example.eml', file, 'binary') }) ``` ```python file = mailosaur.files.get_email('MESSAGE_ID').content f = open('example.eml', 'wb') f.write(file) f.close() ``` ```java byte[] file = mailosaur.files().getEmail("MESSAGE_ID"); Files.write(Paths.get("example.eml"), file); ``` ```dotnet var file = mailosaur.Files.GetEmail("MESSAGE_ID"); File.WriteAllBytes("example.eml", file); ``` ```ruby file = mailosaur.files.get_email('MESSAGE_ID') File.open(first_attachment.file_name, 'wb') { |fp| fp.write(file) } ``` ```php $file = $mailosaur->files->getEmail("MESSAGE_ID"); $f = fopen("example.eml", "w") or die("Unable to open file!"); fwrite($f, $file); fclose($f); ``` ```go var file, _ = m.Files.GetEmail("MESSAGE_ID") var err = os.WriteFile("example.eml", file, 0644) if err != nil { // handle error } ``` ## Analysis The Analysis API allows you to analyse messages in more detail. For example, running a SpamAssassin report. ### Perform a deliverability check `GET /api/analysis/deliverability/:id` Generates a a deliverability report for the specified email. The domain of the sender is checked to ensure the deliverability of the email. Content of the email is also checked to highlight issues that may cause the email to be marked as illegitimate. Content is also checked via SpamAssassin which is one of the most common spam checkers on the market, these results can be used to understand how common spam checkers will view your email. #### Parameters | Name | Type | Location | Required | Description | | --- | --- | --- | --- | --- | | id | string | path | Yes | The identifier of the email to be analyzed. | #### Request ```curl curl \ -u api:YOUR_API_KEY \ https://mailosaur.com/api/analysis/deliverability/MESSAGE_ID ``` ```nodejs const result = await mailosaur.analysis.deliverability(message.id) console.log(result.spf.result) // "Pass" result.spamAssassin.forEach(r => { console.log(r.rule) console.log(r.description) console.log(r.score) }) ``` ```cypress cy.mailosaurGetDeliverabilityReport().then(result => { cy.log(result.spf.result) // "Pass" result.spamAssassin.forEach(r => { cy.log(r.rule) cy.log(r.description) cy.log(r.score) }) }) ``` ```python result = mailosaur.analysis.deliverability(message.id) print(result.spf.result) // "Pass" for r in result.spam_assassin: print(r.rule) print(r.description) print(r.score) ``` ```java DeliverabilityReport result = client.analysis().deliverability(message.id()); System.out.println(result.spf().result()); // "Pass" for (SpamAssassinRule rule : result.spamFilterResults().spamAssassin()) { System.out.println(rule.rule()); System.out.println(rule.description()); } ``` ```dotnet var result = mailosaur.Analysis.Deliverability(message.Id); Console.WriteLine(result.spf.result) // "Pass" foreach (var r in result.SpamAssassin) { Console.WriteLine(r.Rule); Console.WriteLine(r.Description); Console.WriteLine(r.Score); } ``` ```ruby result = mailosaur.analysis.deliverability(message.id) puts(result.spf.result) // "Pass" for r in result.spam_assassin do puts(r.rule) puts(r.description) puts(r.score) end ``` ```php $result = $mailosaur->analysis->deliverability($message->id); print($result->spf->result) // "Pass" foreach ($result->spamAssassin as &$r) { print($r->rule); print($r->description); print($r->score); } ``` ```go result, _ := m.Analysis.Deliverability(message.Id) fmt.Println(result.Spf.Result) // "Pass" for _, r := range result.SpamAssassin { fmt.Println(r.Rule) fmt.Println(r.Description) fmt.Println(r.Score) } ``` ```swift let result = try await EmailsTestsSetup.client.analysis.deliverability(email: message.id) print(result.spf?.result) // "Pass" for rule in result.spamAssassin { print(rule.rule) print(rule.description) print(rule.score) } ``` #### Response ```json { "spf": { "result": "Pass", "description": null, "rawValue": null, "tags": {} }, "dkim": [ { "result": "Pass", "description": null, "rawValue": null, "tags": {} } ], "dmarc": { "result": "Pass", "description": null, "rawValue": "v=DMARC1; p=reject; rua=mailto:dmarc@abc1234.mailosaur.net;", "tags": { "v": "DMARC1", "p": "reject", "rua": "mailto:dmarc@abc1234.mailosaur.net" } }, "blockLists": [ { "id": "ABC123", "name": "ABC", "result": "Pass" }, { "id": "DEF123", "name": "DEF", "result": "Warning" }, { "id": "GHI123", "name": "GHI", "result": "Fail" }, ], "content": { "embed": false, "iframe": false, "object": false, "script": false, "shortUrls": false, "textSize": 123, "totalSize": 3456, "missingAlt": false, "missingListUnsubscribe": false }, "dnsRecords": { "a": [ "mailosaur.net. 30 IN A 192.168.1.1" ], "mx": [ "mailosaur.net. 30 IN MX 0 mailosaur.net." ], "ptr": [] }, "spamAssassin": { "score": 0, "result": "Pass", "rules": [ { "score": 0.0, "rule": "ABC123", "description": "ABC123" } ] } } ``` ## Email Previews The Previews API lets you generate previews of an email in real email clients and devices, then download each preview as an image. To use it in an automated test, see [Automate email previews](/docs/email-previews/automate-previews). The Previews API is available on the Core and Enterprise plans with the Email Previews add-on. It is not available during a free trial. ### List email clients `GET /api/screenshots/clients` Lists the email clients and devices you can generate previews in. Use the `label` of a client to choose it when you [generate email previews](#generate-email-previews). Each label is made up of the device, the email client, light or dark mode, and the orientation. For example, `iphone-16-applemail-darkmode-portrait`. For a readable list, see [Supported email clients and devices](/docs/email-previews/supported-clients). #### Request ```curl curl \ -u api:YOUR_API_KEY \ https://mailosaur.com/api/screenshots/clients ``` ```nodejs const result = await mailosaur.previews.listEmailClients(); ``` ```cypress cy.mailosaurListPreviewEmailClients().then(result => { cy.log(result.items[0].label) }) ``` ```python result = mailosaur.previews.list_email_clients() ``` ```java EmailClientListResult result = mailosaur.previews().listEmailClients(); ``` ```dotnet var result = mailosaur.Previews.ListEmailClients(); ``` ```ruby result = mailosaur.previews.list_email_clients() ``` ```php $result = $mailosaur->previews->allEmailClients(); ``` ```go result, _ := m.Previews.ListEmailClients() ``` #### Response ```json { "items": [ { "label": "windows-outlook-lightmode-landscape", "name": "Windows Outlook Light Mode Landscape" }, { "label": "iphone-16-applemail-darkmode-portrait", "name": "iPhone 16 Apple Mail Dark Mode Portrait" }, { "label": "android-15-gmail-lightmode-portrait", "name": "Android 15 Gmail Light Mode Portrait" } ] } ``` ### Generate email previews `POST /api/messages/:id/screenshots` Generates previews of an email in the email clients you choose. Each preview uses one credit from your monthly limit. See [Usage limits](/docs/managing-your-account/usage-limits). The response lists one preview for each email client. Previews take a short time to render, so a new preview has a `status` of `Pending`. To wait for a preview and download it, see [Download an email preview](#download-an-email-preview). The request fails with a `400` error, and generates no previews, if: - An email client label is not valid. The error suggests a valid label where it can. - The previews would take you over your monthly limit. #### Parameters | Name | Type | Location | Required | Description | | --- | --- | --- | --- | --- | | id | string | path | Yes | The identifier of the email to preview. This can be found via other API calls such as Search for messages. | | emailClients | array | body | Yes | The labels of the email clients to generate previews in. To find the labels, use List email clients. | #### Request ```curl curl \ -X POST \ -H 'Content-Type: application/json' \ -d '{"emailClients":["iphone-16-applemail-darkmode-portrait","windows-outlook-lightmode-landscape"]}' \ -u api:YOUR_API_KEY \ https://mailosaur.com/api/messages/MESSAGE_ID/screenshots ``` ```nodejs // MESSAGE_ID: The `id` of the email you want to preview const result = await mailosaur.messages.generatePreviews('MESSAGE_ID', { emailClients: [ 'iphone-16-applemail-darkmode-portrait', 'windows-outlook-lightmode-landscape' ] }); ``` ```cypress // MESSAGE_ID: The `id` of the email you want to preview cy.mailosaurGenerateEmailPreviews('MESSAGE_ID', { emailClients: [ 'iphone-16-applemail-darkmode-portrait', 'windows-outlook-lightmode-landscape' ] }).then(result => { cy.log(result.items[0].id) }) ``` ```python options = PreviewRequestOptions([ "iphone-16-applemail-darkmode-portrait", "windows-outlook-lightmode-landscape" ]) # MESSAGE_ID: The `id` of the email you want to preview result = mailosaur.messages.generate_previews("MESSAGE_ID", options) ``` ```java PreviewRequestOptions options = new PreviewRequestOptions(); options.withEmailClients(Arrays.asList( "iphone-16-applemail-darkmode-portrait", "windows-outlook-lightmode-landscape" )); // MESSAGE_ID: The `id` of the email you want to preview PreviewListResult result = mailosaur.messages().generatePreviews("MESSAGE_ID", options); ``` ```dotnet var options = new PreviewRequestOptions(new ListHello world.
", attachments: attachments, }); ``` ### Replying to an email If your product is capable of handling customer replies, Mailosaur's reply feature can simulate this. Any reply is sent back to the address it was originally sent from: ```js cy.mailosaurReplyToMessage("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 one-by-one, or via the creation of automated forwarding rules. Before you do this, **you must set up a [verified external email address](/docs/managing-your-account/external-email-addresses)**: ```js cy.mailosaurForwardMessage("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 associated attachments. This operation cannot be undone: ```js cy.mailosaurDeleteMessage("MESSAGE_ID"); ``` ### Delete all messages Permanently deletes all messages and attachments held in the specified inbox. This operation cannot be undone: ```js cy.mailosaurDeleteAllMessages("SERVER_ID"); ``` ## See also - [SMS testing guide](/docs/automation/cypress/sms-testing) - [MFA/2FA guide](/docs/authenticator) --- Source: https://mailosaur.com/docs/automation/cypress/quickstart # Mailosaur and Cypress - Quickstart guide Get Mailosaur up and running within your Cypress project in a few steps. ## What you'll need - A Mailosaur account. If you don't already have one, [create a free trial account](/app/signup). - [An API key](/app/keys). Log in to your account and generate one in order to run automated tests. - Knowledge of how to send emails (or SMS) into your account. ## Express: Generate a sample project If you have **npm** installed, you can generate a basic starter project for Cypress via the command line: ```sh npm create mailosaur@latest ``` This will give you a simple Cypress project with Mailosaur already configured, along with some basic tests that show how a project would typically work. You can also see similar [sample code](https://github.com/mailosaur/examples/tree/main/cypress) on GitHub. ## Integrate with an existing Cypress project If you have an existing Cypress project, or have just created one, you'll need to install and configure Mailosaur's API client library: ### Install the Mailosaur plugin Mailosaur provides an official set of custom commands for automating email testing in Cypress. Extend Cypress by installing Mailosaur’s custom commands package: [cypress-mailosaur](https://github.com/mailosaur/cypress-mailosaur). 1. Install the plugin via `npm`: ```bash npm install cypress-mailosaur ``` 2. Open `cypress/support/e2e.js` in your project folder, and add the following line of code to it: ```js import "cypress-mailosaur"; ``` 3. Add your [Mailosaur API key](/app/keys) to `cypress.config.js`, in your project folder: ```js module.exports = defineConfig({ env: { MAILOSAUR_API_KEY: "YOUR_API_KEY", }, // ... }); ``` **Note:** We strongly recommend against storing API keys in source control. Therefore you can also set your API key using the environment variable `CYPRESS_MAILOSAUR_API_KEY`. ### Make your first API call ```js // Make a simple API call to find the name of your inbox cy.mailosaurListServers().then((result) => { cy.log(`Inbox name is ${result.items[0].name}`); }); ``` ## Start testing Now that you have a project connected to the Mailosaur API, you can start creating a variety of tests: - [Email testing](/docs/automation/cypress/email-testing) - test password resets, account verification, order confirmations, etc. - [SMS testing](/docs/automation/cypress/sms-testing) - test alerts, notifications, and 2FA logins - [2FA app testing](/docs/authenticator) - mimic the functionality of apps like Google Authenticator and Auth0 - [Email deliverability testing](/docs/api) --- Source: https://mailosaur.com/docs/automation/cypress/sms-testing # SMS testing for Cypress Learn how to test every element of your SMS communication within Cypress. ## What you'll find in this guide - How to test various aspects of SMS - Testing links and codes - Managing SMS tests ## What you'll need - An understanding of how to use Cypress. - A Mailosaur account with the SMS feature enabled. If you don't have one already, you can [start a free trial](/app/signup). - A Cypress project with Mailosaur's API client configured. [See our short guide](/docs/automation/cypress/quickstart) on this. ## Basic usage To perform SMS testing with Cypress, all you need to do is: 1. Send an SMS message to your dedicated Mailosaur phone number. 2. Connect to the Mailosaur API with the official client library. 3. Search for the message you sent in step 1. 4. Perform assertions in the same way you would for any other test. If you would like 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 // Search for the message cy.mailosaurGetMessage("SERVER_ID", { sentTo: "123456789", // Phone number }).then((message) => { // Perform test assertions expect(message.from[0].name).to.equal("Support"); expect(message.from[0].phone).to.equal("654321"); }); ``` The above example will search for the phone number that a message was sent to. You can also use any of the below criteria to search: | **Parameter** | **Description** | | ------------- | ------------------------------------------------------------ | | sentTo | The full phone number to which the target message was sent | | sentFrom | The full phone number from which the target message was sent | | body | Finds messages where the message body contains this text | ## Find an SMS message Search for a specific message in your inbox. We recommend using `cy.mailosaurGetMessage()`, as this will automatically wait for messages to arrive, and then return the full message result. ```js cy.mailosaurGetMessage("SERVER_ID", { sentTo: "123456789", }).then((message) => { cy.log(message.text.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 cy.mailosaurGetMessage("SERVER_ID", { sentTo: "123456789", }, { receivedAfter: yesterday }).then((message) => { }); ``` ### "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 methods of fetching SMS messages > [!WARNING] > > #### It is usually better to use `cy.mailosaurGetMessage()` > > The `mailosaurListMessages` and `mailosaurSearchMessages` methods will only return basic summaries, leaving certain properties, such as the message body, out. To get this data, use `cy.mailosaurGetMessageById()`. We recommend using the `cy.mailosaurGetMessage()` as this automatically waits for a matching result and returns the message. ### Search for multiple messages Identify if multiple messages meet the same criteria. ```js // Search for all messages sent to 123456789. // Limit results to the first 10 matches only. cy.mailosaurSearchMessages( "SERVER_ID", { sentTo: "123456789", }, { page: 0, itemsPerPage: 10, } ) .then((result) => { // Get the most recent message (the first one in the list) const latestMessage = result.items[0]; // Get the full message object return cy.mailosaurGetMessageById(latestMessage.id); }) .then((message) => { cy.log(message.text.body); }); ``` ### List current inbox contents List everything that is currently in your inbox. ```js // List the most recent messages cy.mailosaurListMessages("SERVER_ID") .then((result) => { // Get the most recent message (the first one in the list) const latestMessage = result.items[0]; // Get the full message object return cy.mailosaurGetMessageById(latestMessage.id); }) .then((message) => { cy.log(message.text.body); }); ``` ## Common test scenarios ### Testing basic properties Once an SMS has been retrieved, you can effectively test the properties of that text: ```js // Test sender information expect(message.from[0].name).to.equal("Support"); expect(message.from[0].phone).to.equal("654321"); // Test recipient information expect(message.to[0].name).to.equal("John Smith"); expect(message.to[0].phone).to.equal("1234567890"); ``` ### Testing SMS contents The content of an SMS message is available via the `text.body` property: ```js cy.log(message.text.body); // "Hi Jason, ..." ``` ### Testing links Any links found in SMS content are automatically available via the `text.links` array: ```js // How many links? cy.log(message.text.links.length); // 2 const firstLink = message.text.links[0]; expect(firstLink.text).to.equal("Google Search"); expect(firstLink.href).to.equal("https://www.google.com/"); ``` ### Testing verification codes Codes are automatically extracted from the content of your SMS message. They are available via the `text.codes` array: ```js const otp = message.text.codes[0]; expect(otp.value).to.equal("456812"); ``` ### Replying to an SMS message If your product handles SMS replies from your customers, you can use Mailosaur’s reply feature to simulate responses. The SMS is sent back to the phone number it was originally sent to Mailosaur from: ```js cy.mailosaurReplyToMessage("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 automated forwarding rules. However, to forward messages, **you must set up a [verified external email address](/docs/managing-your-account/external-email-addresses)**: ```js cy.mailosaurForwardMessage("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 it. This operation cannot be undone: ```js cy.mailosaurDeleteMessage("MESSAGE_ID"); ``` ### Delete all messages Permanently deletes all messages held in the specified inbox, along with all related attachments. This operation cannot be undone: ```js cy.mailosaurDeleteAllMessages("SERVER_ID"); ``` ## See also - [Email testing guide](/docs/automation/cypress/email-testing) - [MFA/2FA guide](/docs/authenticator) --- Source: https://mailosaur.com/docs/automation/dotnet # How to test email and SMS in .NET Learn how to automate testing of email and SMS messages in .NET, using Mailosaur. ## 1. Create a Mailosaur account If you already have an account, skip to step 2. To create a new trial account, [sign up here](/app/signup). ## 2. Create a sample project ### Install .NET To see if you already have .NET installed, open a terminal window and run this command: ```bash dotnet --version ``` If .NET is installed, you’ll see a version number. If you see an error instead, then [download .NET from Microsoft](https://dotnet.microsoft.com/en-us) and install it. ### Create a new project Run each of these commands to create a new .NET project: ```bash mkdir EmailTests cd EmailTests dotnet new console ``` ### Install the Mailosaur .NET library Run this command to install the [Mailosaur NuGet package](https://github.com/mailosaur/mailosaur-dotnet): ```bash dotnet add package mailosaur ``` ## 3. Send email to your Mailosaur inbox Inboxes allow you to group tests, permissions, and other settings together. Each inbox has an **Inbox ID** and a **domain name**. You need these values to both send email to Mailosaur, and to set up automated testing. You also need an [API key](/docs/managing-your-account/api-keys) to use. You can learn more about [creating API keys here](/docs/managing-your-account/api-keys). ### Retrieve your inbox’s attributes 1. In the left-hand navigation, locate the **Inboxes** section. 2. Click on the name of the inbox you want to test with. 3. Click the **Settings** tab. 4. Make a note of the **Inbox ID** and **Domain**. 5. Get an API key from the [API Keys](/app/keys) page. ### Send an email to your inbox If the **domain name** of your inbox above was: ```bash example.mailosaur.net ``` Then you can send an email to it with these steps: 1. Open up an email client and send an email to `anything@example.mailosaur.net` 2. In the left-hand navigation, locate the **Inboxes** section. 3. Click on the name of the inbox you sent an email to. 4. Confirm the email is there. Note that some services (like Gmail) may take 10-20 seconds to send a message through. To learn more, read our guide on [sending email to Mailosaur](/docs/email-testing/sending-to-mailosaur). ## 4. Find an email for automated testing Now that you have a sample project, your inbox’s credentials, and an email to test, then you’re ready to continue. Open the file in your new project called `Program.cs` and type or paste in this code sample, replacing the template code with the values from step 3 above: ```csharp using System; using Mailosaur; using Mailosaur.Models; namespace EmailTests { class Program { static void Main(string[] args) { // Find these on the API Keys page and your inbox's Settings tab var apiKey = "YOUR_API_KEY"; var serverId = "SERVER_ID"; var serverDomain = "SERVER_DOMAIN"; var mailosaur = new MailosaurClient(apiKey); // Wait for an email to arrive, matching this search criteria var criteria = new SearchCriteria() { SentTo = "anything@" + serverDomain }; var email = mailosaur.Messages.Get(serverId, criteria); // If we have an email, print the subject Console.WriteLine("Subject: " + email.Subject); } } } ``` This code connects to Mailosaur and looks for any email that has been sent to the address provided in the search criteria. Save your changes and run the code: ```bash dotnet run ``` If everything is set up correctly, you should see the subject line of the last email you sent, printed to screen: ```bash Subject: My example email ``` ### Troubleshooting If you see an error, e.g. ‘No matching messages found in time’: - Make sure you have set the **sent to** address correctly in your code. - Ensure that you have sent an email to the **sent to** address (check this is visible in the Mailosaur Dashboard). - Note that by default, the **get** method will only look for messages that were received by Mailosaur within the last hour. You can override this using the `receivedAfter` option (see library reference below). ## 5. Narrowing your search results ### Only find messages received after a certain time By default, searches include messages received in the last hour, but you can customise the search window with the `receivedAfter` option. This example shows you how to only include emails received after your test started: ```csharp var testStart = DateTime.UtcNow; // Perform the steps that send a message here var criteria = new SearchCriteria() { SentTo = "..." }; var message = mailosaur.Messages.Get( "SERVER_ID", criteria, receivedAfter: testStart ); ``` ### Search criteria As you can see in the examples so far, you can search for the email address or phone number a message was sent to, but you can also search using these criteria: | PARAMETER | DESCRIPTION | | ------------ | ------------ | | **SentFrom** | The full email address from which the target message was sent. | | **SentTo** | The full email address to which the target message was sent. | | **Subject** | Find emails where the subject line contains this text. | | **Body** | Finds messages where the message body contains this text. | ## 6. Start writing tests Now that you have a working project that fetches an email, you can use this to begin writing tests for various pieces of functionality. Check out these guides on the most common test cases: > [!LINK](/docs/automation/text-content) > ### How to test the text content of email or SMS > Learn how to test the text content of email or SMS with Mailosaur. > [!LINK](/docs/automation/html-content) > ### HTML content of an email > Learn how to work with the HTML content found within your emails. > [!LINK](/docs/automation/codes) > ### Extracting codes from email and SMS > Learn how to test verification codes found in email and SMS messages with Mailosaur. > [!LINK](/docs/automation/links) > ### Extracting links from email and SMS > Learn how to test hyperlinks found in email and SMS messages with Mailosaur. > [!LINK](/docs/automation/attachments) > ### Email attachments > Learn how to test the email attachments with Mailosaur. > [!LINK](/docs/automation/images) > ### Images and web beacons > Learn how to work with images, including web beacons, within an HTML email. > [!LINK](/docs/automation/message-properties) > ### Message properties > Learn how to test the common properties of an email or SMS message with Mailosaur. > [!LINK](/docs/automation/spam) > ### How to test email spam score > Learn how to test the SpamAssassin score of an email with Mailosaur. ## SMS Testing You can test SMS messages in much the same way as email. Take a look at our [guide on testing SMS messages](/docs/sms-testing) for more information. ## Library reference The .NET client library gives you access to several other methods. ### Messages Messages is the collective name given to the email and/or SMS messages that are sent into Mailosaur for testing. The [message object](/docs/api) contains everything you need to perform in-depth automated testing. #### Messages.Get(server, criteria, options) Waits for a message to be found. Returns as soon as a message matching the specified search criteria is found. This is the most efficient method of looking up a message, therefore we recommend using it whenever possible. ```csharp var message = mailosaur.Messages.Get("SERVER_ID", new SearchCriteria() { SentTo = "someone@SERVER_ID.mailosaur.net" }); ``` To learn about inbox IDs, and what to replace `SERVER_ID` with, see [sending email to Mailosaur](/docs/email-testing/sending-to-mailosaur). ##### Criteria | PARAMETER | DESCRIPTION | | ------------ | ------------ | | **SentFrom** | The full email address from which the target message was sent. | | **SentTo** | The full email address to which the target message was sent. | | **Subject** | The subject line of the target email. | | **Body** | Search for part of the message body. | | **Match** | If set to `ALL` (default), then only results that match all specified criteria will be returned. If set to `ANY`, results that match any of the specified criteria will be returned. | ##### Options | PARAMETER | DESCRIPTION | | ------------ | ------------ | | **timeout** | Specify how long to wait for a matching result (in milliseconds, _default value is 10 seconds_). | | **receivedAfter** | Limits results to only messages received after this date/time (_default 1 hour ago_). | ```csharp // Search all messages received after midnight on a specific var message = mailosaur.Messages.Get("SERVER_ID", new SearchCriteria() { SentTo = "someone@SERVER_ID.mailosaur.net" }, receivedAfter: new DateTime(2020, 1, 5)); ``` #### Messages.List(server, options) Returns a list of your messages in summary form. The summaries are returned sorted by received date, with the most recently-received messages appearing first. > [!SUCCESS] > The method returns a message summary, rather than the full message object. This means that several properties, like the message body, are not included. To get this data, you’ll need to call [`GetById`](#messagesgetbyidid). Alternatively, we recommend using the [`Get`](#messagesgetserver-criteria-options) method, which is a far more efficient approach. ```csharp // List the most recent messages var result = mailosaur.Messages.List("SERVER_ID"); // Get the most recent message (the first one in the list) var message = result.Items[0]; Console.WriteLine("Subject: " + message.Subject); ``` ##### Options - **receivedAfter** Allows you to customise how far back to look for messages. - **page** Used alongside `itemsPerPage` to paginate through results. This is zero-based, meaning `0` is the first page of results. - **itemsPerPage** A limit on the number of results to be returned. This can be set between 1 to 1000, with the default being 50. - **dir** Optionally limits results based on the direction (`Sent` or `Received`), with the default being `Received`. ```csharp // List all results received after midnight on a specific date // Limit results to the first 10 matches only. var result = mailosaur.Messages.List("SERVER_ID", 0, 10, new DateTime(2020, 1, 3)); ``` #### Messages.Search(server, criteria, options) Returns a list of messages matching the specified search criteria, in summary form. The messages are returned sorted by received date, with the most recently-received messages appearing first. > [!SUCCESS] > The method returns a message summary, rather than the full message object. This means that several properties, like the message body, are not included. To get this data, you’ll need to call [`GetById`](#messagesgetbyidid). Alternatively, we recommend using the [`Get`](#messagesgetserver-criteria-options) method, which is a far more efficient approach. ```csharp var result = mailosaur.Messages.Search("SERVER_ID", new SearchCriteria() { SentTo = "someone@SERVER_ID.mailosaur.net" }); // Get the most recent match var message = result.Items[0]; Console.WriteLine("Subject: " + message.Subject); ``` ##### Criteria | PARAMETER | DESCRIPTION | | ------------ | ------------ | | **SentFrom** | The full email address from which the target message was sent. | | **SentTo** | The full email address to which the target message was sent. | | **Subject** | The subject line of the target email. | | **Body** | Search for part of the message body. | | **Match** | If set to `ALL` (default), then only results that match all specified criteria will be returned. If set to `ANY`, results that match any of the specified criteria will be returned. | ##### Options | PARAMETER | DESCRIPTION | | ------------ | ------------ | | **timeout** | If provided, determines how long to wait for a matching result (provided in milliseconds). | | **errorOnTimeout** | When set to `false`, an error will not be thrown if timeout is reached (default: `true`). | | **receivedAfter** | Allows you to customise how far back to look for messages. | | **page** | Used alongside `itemsPerPage` to paginate through results. This is zero-based, meaning `0` is the first page of results. | | **itemsPerPage** | A limit on the number of results to be returned. This can be set between 1 to 1000, with the default being 50. | | **dir** | Optionally limits results based on the direction (`Sent` or `Received`), with the default being `Received`. | ```csharp // Search for all messages sent to someone@SERVER_ID.mailosaur.net, // received after midnight on a specific date. Limit results to // the first 10 matches only. var result = mailosaur.Messages.Search("SERVER_ID", new SearchCriteria() { SentTo = "someone@SERVER_ID.mailosaur.net" }, page: 0, itemsPerPage: 10, receivedAfter: new DateTime(2020, 1, 3)); ``` #### Messages.GetById(id) Retrieves the detail for a single email message. Must be used in conjunction with either [`List`](#messageslistserver-options) or [`Search`](#messagessearchserver-criteria-options) in order to get the unique identifier for the required message. **We always recommend using the** [`Get`](#messagesgetserver-criteria-options) **method instead**. ```csharp var result = mailosaur.Messages.List("SERVER_ID"); var messageId = result.Items[0].Id; var message = mailosaur.Messages.GetById(messageId); Console.WriteLine("Subject: " + message.Subject); ``` #### Messages.Delete(id) Permanently deletes a message. Also deletes any attachments related to the message. This operation cannot be undone. ```csharp mailosaur.Messages.Delete(messageId); ``` #### Messages.DeleteAll(server) Permanently deletes all messages held in the specified inbox. Also deletes any attachments related to each message. This operation cannot be undone. ```csharp mailosaur.Messages.DeleteAll("SERVER_ID"); ``` #### Messages.Create(server, messageCreateOptions) Creates a new message that can be sent to a verified email address. This is useful in scenarios where you want an email to trigger a workflow in your product. ```csharp mailosaur.Messages.Create("SERVER_ID", new MessageCreateOptions() { To = "verified-address@example.com", Send = true, Subject = "Request" Text = "Please can you give us a call back?" }); ``` ##### Options - **to** The email address to which the email will be sent. Must be a verified email address. - **send** If true, email will be sent upon creation. - **subject** The email subject line. - **text** The plain text body of the email. - **html** The HTML body of the email. #### Messages.Forward(messageId, messageForwardOptions) Forwards the specified email to a verified email address. ```csharp mailosaur.Messages.Forward("MESSAGE_ID", new MessageForwardOptions() { To = "verified-address@example.com", Text = "FYI" }); ``` ##### Options - **to** The email address to which the email will be sent. Must be a verified email address. - **text** Any additional plain text content to forward the email with. - **html** Any additional HTML content to forward the email with. #### Messages.Reply(messageId, messageReplyOptions) Sends a reply to the specified email. This is useful for when simulating a user replying to one of your emails. ```csharp mailosaur.Messages.Reply("MESSAGE_ID", new MessageReplyOptions() { Text = "FYI" }); ``` ##### Options - **text** Any additional plain text content to include in the reply. - **html** Any additional HTML content to include in the reply. ### Servers Inboxes capture emails and SMS messages, group your tests and settings, and manage access for your team. #### Servers.List() Returns a list of your inboxes. Inboxes are returned sorted in alphabetical order. ```csharp ServerListResult result = mailosaur.Servers.List(); Console.WriteLine("You have an inbox called: " + result.Items[0].Name); ``` #### Servers.Create(server) Creates a new inbox. Only the `name` property is required to create a new inbox via the API. ```csharp var options = new ServerCreateOptions("My email tests"); mailosaur.Servers.Create(options); ``` #### Servers.Get(id) Retrieves the detail for a single inbox. Simply supply the unique identifier for the required inbox. ```csharp var server = mailosaur.Servers.Get("SERVER_ID"); ``` #### Servers.GetPassword(id) Retrieves the password, for use with SMTP and POP3, for a single inbox. Simply supply the unique identifier for the required inbox. ```csharp var password = mailosaur.Servers.GetPassword("SERVER_ID"); ``` #### Servers.Update(id, server) Updates a single inbox. ```csharp var retrievedServer = mailosaur.Servers.Get("SERVER_ID"); retrievedServer.Name = "Updated inbox name"; mailosaur.Servers.Update(retrievedServer.Id, retrievedServer); ``` #### Servers.Delete(id) Permanently deletes an inbox. Also deletes all messages and associated attachments within the inbox. This operation cannot be undone. ```csharp mailosaur.Servers.Delete("SERVER_ID"); ``` #### Servers.GenerateEmailAddress(id) Utility method to help you generate a random email address for a given inbox. ```csharp var emailAddress = mailosaur.Servers.GenerateEmailAddress("SERVER_ID"); Console.WriteLine(emailAddress); // "bgwqj@SERVER_ID.mailosaur.net" ``` To learn about inbox IDs, and what to replace `SERVER_ID` with, see [sending email to Mailosaur](/docs/email-testing/sending-to-mailosaur). ### Files #### Files.GetEmail(messageId) Downloads an EML file representing the specified email. Simply supply the unique identifier for the required email. #### Files.GetAttachment(attachmentId) Downloads a single attachment. Simply supply the unique identifier for the required attachment. ### Analysis #### Analysis.Spam(messageId) Perform spam testing on the specified email. ### Usage #### Usage.Limits() Retrieve account usage limits. Details the current limits and usage for your account. This endpoint requires authentication with an account-level API key. #### Usage.Transactions() Retrieves the last 31 days of transactional usage. This endpoint requires authentication with an account-level API key. --- Source: https://mailosaur.com/docs/automation/ghost-inspector # How to test email and SMS using Ghost Inspector Test email and SMS with Ghost Inspector - the all-in-one website test and monitoring service and Mailosaur, the number one email and SMS testing service. ## What is Ghost Inspector? [Ghost Inspector](https://ghostinspector.com) lets you create automated website tests and set up monitoring suites. It makes automated testing for websites and web apps easier, especially with its [web test recorder](https://docs.ghostinspector.com/test-recorder), which allows you to easily record tests from right within your web browser. As you're here, there is a good chance you know about Ghost Inspector already, but if you don't, we highly recommend their [official getting started guide and video](https://ghostinspector.com/docs/getting-started). ## What is Mailosaur? Mailosaur lets you test email and SMS messages as part of your end-to-end automated testing. This is particularly important for websites and web apps that send an email (password resets, account setup, marketing emails, etc.) or SMS message (multi-factor authentication, verification, etc.). If you don’t already have one, you’ll need to [create a free trial account](/app/signup). Once you’re in, familiarize yourself with [sending email into Mailosaur](/docs/email-testing/sending-to-mailosaur). Once you have this working, you’re ready to start testing! ## 1. Get Started ### Creating an account Create a [free trial account](/app/signup) for Mailosaur via the website. Once you have this, open your inbox from the **Inboxes** section of the left-hand navigation, then click the **Settings** tab. You need the following values: - **Inbox ID** - Every [inbox](/docs/inboxes) has a unique ID. You need this ID whenever you interact with an inbox via the API. - **Inbox Domain** - Every inbox has its own domain name. You'll need this to send email to your inbox. - **API Key** - Get one from the [API Keys](/app/keys) page. You can create an API key per inbox (recommended), or an account-level API key to use across your whole account. [Learn more about API keys](/docs/managing-your-account/api-keys). ### Test email addresses with Mailosaur Mailosaur gives you an unlimited number of test email addresses - with no setup or coding required! This is because every inbox uses a catch-all/wildcard pattern. Here's what that means: - When you create an account, you are given an inbox. - Every inbox has its own **Inbox Domain** name (e.g. `abc123.mailosaur.net`) - Any email address that ends with `@{YOUR_SERVER_DOMAIN}` will work with Mailosaur without any special setup. For example: - `build-423@abc123.mailosaur.net` - `john.smith@abc123.mailosaur.net` - `rAnDoM63423@abc123.mailosaur.net` - You can create more inboxes when you need them. Each one will have its own domain name. > [!INFO] > You can also [use SMTP to test email](/docs/email-testing/sending-to-mailosaur#0-sending-directly-via-smtp). By connecting your product or website to Mailosaur via SMTP, Mailosaur will catch all email your application sends, regardless of the email address. ### Understanding the API Because Ghost Inspector runs all your tests in the browser, we’re going to use [Mailosaur.js](/docs/automation/javascript) (our client-side API library). This guide will take you through all the key use cases, but it’s worth remembering that the library is powered by the Mailosaur [Email & SMS Testing API](/docs/api). You can easily check out the API itself by looking at our [API reference documentation](/docs/api) or via our Postman or Insomnia collections:   ## 2. Create a new Ghost Inspector test suite Navigate to [Ghost Inspector](https://app.ghostinspector.com), and create a new test suite. This is done by clicking **New > New suite** in the top-right of the page. Give your suite a name and click **Create Suite**. ## 3. Add steps that trigger an email You now need some test steps that will cause an email to be sent from your website or product. As discussed above, you have an unlimited number of [test email addresses](#0-test-email-addresses-with-mailosaur) with Mailosaur. In this example, we will navigate to the [Mailosaur Playground](https://example.mailosaur.com) to mimic a real world product that has a password reset feature. Ghost Inspector has an awesome browser extension to allow you to quickly record these steps yourself in the browser, but in this guide we’re going to do this manually, because that’s how we roll… 💪 1. Under **Create new test**, on the right of the screen, we type “Request Password Reset”. 2. Next, input the starting URL (in our example, that's `https://example.mailosaur.com/password-reset`). 3. Click **Create**. 4. Next, add a step to fill in the email address on the password reset form. In the screenshot below you can see we use an **Assign** step to set the input field (`#email`) to our test email address of `ghost-inspector@abc123.mailosaur.net`. Note that `abc123.mailosaur.net` is our Inbox Domain (from step 1 above), and `ghost-inspector` is any string we want (you don’t need to create email addresses with Mailosaur). 5. Finally, add a step to submit the password reset request - a simple button click is all we need. Running this test allows us to successfully _request_ a password reset. But to complete the process, we need to find that email and follow the link inside it. ## 4. Find the email ### Using Mailosaur.js in a web browser Mailosaur has libraries to write tests in [various languages](/docs/automation). As Ghost Inspector runs in the browser, we need to use [Mailosaur.js](/docs/automation/javascript) which allows us to do email and SMS testing from within a web browser. To do this, **you must first** [verify your website or web app's domain name](/docs/managing-your-account/managing-domains). Go to the [Domains](/app/account/domains) section of the Mailosaur Dashboard, and follow the on-screen instructions to add a new verified domain. ### Execute JavaScript to import the Mailosaur.js library To pull [Mailosaur.js](/docs/automation/javascript) into our Ghost Inspector test, add an **Execute JavaScript** step, with the following code: ```js (function (e, m, a, i, l) { i = e.createElement(m), l = e.getElementsByTagName(m)[0]; i.async = 1; i.src = a; e.body.appendChild(i) })(document, 'script', 'https://mailosaur.com/v1/mailosaur.js'); ``` ### Extract the email into a variable Next, we need to find our email and extract the result into a variable that we can use else where in our Ghost Inspector suite. To do this, add an **Extract from JavaScript** step, with the following code (note that we [discussed the values](#0-creating-an-account) to use for `apiKey` and `serverId` [above](#0-creating-an-account)): ```js return new Promise(function (resolve, reject) { const apiKey = 'YOUR_API_KEY'; const serverId = 'abc123'; const mailosaur = Mailosaur(apiKey); const promise = mailosaur.messages.get(serverId, { sentTo: 'ghost-inspector@abc123.mailosaur.net' }); promise.then(resolve).catch(reject); }) ``` In the **Variable name** field, type “message”. Let’s break down what the code above actually does: - First, it is an async method, so Ghost Inspector requires that we first return a Promise. - Inside that, we set variables for our `apiKey` and `serverId`, the values for which we [discussed above](/docs/automation/ghost-inspector#0-creating-an-account). - Finally, we have an async method that searches for the email we sent (using `mailosaur.messages.get`) and resolves the result. In this example we are searching for our message using the `sentTo` option. You can search using any of the criteria [described in the API reference](/docs/api#4-search-for-messages). ## 5. Create an assertion step Now that we have our email in a variable, we can start creating assertions. This can be done by adding a **JavaScript returns true** step in Ghost Inspector. For example, this will test the email’s subject line: ```js const email = {{message}}; return email.subject === 'Set your new password for ACME Product'; ``` You’re now ready to write whatever tests you need. The rest of this guide will take you through some of the most common things you might want to test. ## Testing plain text content Most emails, and all SMS messages, should have a plain text body. Mailosaur exposes this content via the `text.body` property on an email or SMS message: ```js console.log(message.text.body) // "Hi Jason, ..." if (message.text.body.indexOf('Jason') > -1) { console.log('Email contains "Jason"') } ``` ### Extracting verification codes from plain text You may have an email or SMS message that contains an account verification code, or some other one-time passcode. You can extract content like this using a simple regex. Here is how to extract a 6-digit numeric code: ```js console.log(message.text.body) // "Your access code is 243546." const regEx = new RegExp('([0-9]{6})') const matches = regEx.exec(message.text.body) console.log(matches[0]) // "243546" ``` ## Testing HTML content Most emails also have an HTML body, as well as the plain text content. You can access HTML content in a very similar way to plain text: ```js console.log(message.html.body) // "`) and area (``) elements and makes these available via the `html.links` array. Each link has a text property, representing the display text of the hyperlink within the body, and an href property containing the target URL: ```js // How many links? console.log(message.html.links.length) // 2 const firstLink = message.html.links[0] console.log(firstLink.text) // "Google Search" console.log(firstLink.href) // "https://www.google.com/" ``` **Important:** To ensure you always have valid emails, Mailosaur only extracts links that have been correctly marked up with `` or `` tags. ### Links in plain text (including SMS messages) Mailosaur auto-detects links in plain text content too, which is especially useful for SMS testing: ```js // How many links? console.log(message.text.links.length) // 2 const firstLink = message.text.links[0] console.log(firstLink.href) // "https://www.google.com/" ``` ## Working with attachments If your email includes attachments, you can access these via the attachments property: ```js // How many attachments? console.log(message.attachments.length) // 2 ``` Each attachment contains metadata on the file name and content type: ```js const firstAttachment = message.attachments[0] console.log(firstAttachment.fileName) // "contract.pdf" console.log(firstAttachment.contentType) // "application/pdf" ``` The `length` property returns the size of the attached file (in bytes): ```js const firstAttachment = message.attachments[0] console.log(firstAttachment.length) // 4028 ``` ## Working with images and web beacons The `html.images` property of a message contains an array of images found within the HTML content of an email. The length of this array corresponds to the number of images found within an email: ```js // How many images in the email? console.log(message.html.images.length) // 1 ``` ### Remotely-hosted images Emails will often contain many images that are hosted elsewhere, such as on your website or product. It is recommended to check that these images are accessible by your recipients. All images should have an alternative text description, which can be checked using the `alt` attribute. ```js const image = message.html.images[0] console.log(image.alt) // "Hot air balloon" ``` ### Triggering web beacons A web beacon is a small image that can be used to track whether an email has been opened by a recipient. Because a web beacon is simply another form of remotely-hosted image, you can export the `src` attribute via an **Extract from JavaScript** step, then navigate to that URL using Ghost Inspector: ```js const image = message.html.images[0] return image.src // Extract this value, so you can navigate to it ``` ## Spam checking You can perform a [SpamAssassin](https://spamassassin.apache.org) check against an email. The structure returned matches the [spam test object](/docs/api#0-perform-a-spam-test): ```js const result = await mailosaur.analysis.spam(message.id) console.log(result.score) // 0.5 result.spamFilterResults.spamAssassin.forEach(r => { console.log(r.rule) console.log(r.description) console.log(r.score) }) ``` --- Source: https://mailosaur.com/docs/automation/go # How to test email and SMS in Go Learn how to automate testing of email and SMS messages in Golang, using Mailosaur. ## 1. Create a Mailosaur account If you already have an account, skip to step 2. To create a new trial account, [sign up here](/app/signup). ## 2. Create a sample project ### Install Go To see if you already have Go installed, open a terminal window and run this command: ```bash go version ``` If Go is installed, you’ll see a version number. If you see an error instead, then [download Go from its official site](https://go.dev) and install it. ### Create a new project Run each of these commands to create a new project: ```bash mkdir EmailTests cd EmailTests go mod init example.com/emailtests ``` ### Install the Mailosaur Go library Run this command to install the [Mailosaur Go package](https://github.com/mailosaur/mailosaur-go): ```bash go get -u github.com/mailosaur/mailosaur-go ``` ## 3. Send email to your Mailosaur inbox Inboxes allow you to group tests, permissions, and other settings together. Each inbox has an **Inbox ID** and a **domain name**. You need these values to both send email to Mailosaur, and to set up automated testing. You also need an [API key](/docs/managing-your-account/api-keys) to use. You can learn more about [creating API keys here](/docs/managing-your-account/api-keys). ### Retrieve your inbox’s attributes 1. In the left-hand navigation, locate the **Inboxes** section. 2. Click on the name of the inbox you want to test with. 3. Click the **Settings** tab. 4. Make a note of the **Inbox ID** and **Domain**. 5. Get an API key from the [API Keys](/app/keys) page. ### Send an email to your inbox If the **domain name** of your inbox above was: ```bash example.mailosaur.net ``` Then you can send an email to it with these steps: 1. Open up an email client and send an email to `anything@example.mailosaur.net` 2. In the left-hand navigation, locate the **Inboxes** section. 3. Click on the name of the inbox you sent an email to. 4. Confirm the email is there. Note that some services (like Gmail) may take 10-20 seconds to send a message through. To learn more, read our guide on [sending email to Mailosaur](/docs/email-testing/sending-to-mailosaur). ## 4. Find an email for automated testing Now that you have a sample project, your inbox’s credentials, and an email to test, then you’re ready to continue. Create a file named `hello_test.go` and type or paste in this code sample, replacing the template code with the values from step 3 above: ```go package emailtests import ( "fmt" "testing" "github.com/mailosaur/mailosaur-go" ) func TestExample(t *testing.T) { // Find these on the API Keys page and your inbox's Settings tab apiKey := "YOUR_API_KEY"; serverId := "SERVER_ID"; serverDomain := "SERVER_DOMAIN"; m := mailosaur.New(apiKey); params := &mailosaur.MessageSearchParams { Server: serverId, } criteria := &mailosaur.SearchCriteria { SentTo: "anything@" + serverDomain, } email, err := m.Messages.Get(params, criteria) if (err != nil) { t.Error(err) } // If we have an email, print the subject fmt.Println("Subject: " + email.Subject) } ``` This code connects to Mailosaur and looks for any email that has been sent to the address provided in the search criteria. Save your changes and run the code: ```bash go test ``` If everything is set up correctly, you should see the subject line of the last email you sent, printed to screen: ```bash Subject: My example email ``` ### Troubleshooting If you see an error, e.g. ‘No matching messages found in time’: - Make sure you have set the **sent to** address correctly in your code. - Ensure that you have sent an email to the **sent to** address (check this is visible in the Mailosaur Dashboard). - Note that by default, the **get** method will only look for messages that were received by Mailosaur within the last hour. You can override this using the `ReceivedAfter` option (see library reference below). ## 5. Narrowing your search results ### Only find messages received after a certain time By default, searches include messages received in the last hour, but you can customise the search window with the `ReceivedAfter` option. This example shows you how to only include emails received after your test started: ```go testStart := time.Now() // Perform the steps that send a message here message, _ := client.Messages.Get(&MessageSearchParams{ Server: "SERVER_ID", ReceivedAfter: testStart, }, &SearchCriteria{ SentTo: "...", }) ``` ### Search criteria As you can see in the examples so far, you can search for the email address or phone number a message was sent to, but you can also search using these criteria: | PARAMETER | DESCRIPTION | | ------------ | ------------ | | **SentFrom** | The full email address from which the target message was sent. | | **SentTo** | The full email address to which the target message was sent. | | **Subject** | Find emails where the subject line contains this text. | | **Body** | Finds messages where the message body contains this text. | ## 6. Start writing tests Now that you have a working project that fetches an email, you can use this to begin writing tests for various pieces of functionality. Check out these guides on the most common test cases: > [!LINK](/docs/automation/text-content) > ### How to test the text content of email or SMS > Learn how to test the text content of email or SMS with Mailosaur. > [!LINK](/docs/automation/html-content) > ### HTML content of an email > Learn how to work with the HTML content found within your emails. > [!LINK](/docs/automation/codes) > ### Extracting codes from email and SMS > Learn how to test verification codes found in email and SMS messages with Mailosaur. > [!LINK](/docs/automation/links) > ### Extracting links from email and SMS > Learn how to test hyperlinks found in email and SMS messages with Mailosaur. > [!LINK](/docs/automation/attachments) > ### Email attachments > Learn how to test the email attachments with Mailosaur. > [!LINK](/docs/automation/images) > ### Images and web beacons > Learn how to work with images, including web beacons, within an HTML email. > [!LINK](/docs/automation/message-properties) > ### Message properties > Learn how to test the common properties of an email or SMS message with Mailosaur. > [!LINK](/docs/automation/spam) > ### How to test email spam score > Learn how to test the SpamAssassin score of an email with Mailosaur. ## SMS Testing You can test SMS messages in much the same way as email. Take a look at our [guide on testing SMS messages](/docs/sms-testing) for more information. ## Library reference The Go client library gives you access to several other methods. ### Messages Messages is the collective name given to the email and/or SMS messages that are sent into Mailosaur for testing. The [message object](/docs/api) contains everything you need to perform in-depth automated testing. #### Messages.Get(params, criteria, options) Waits for a message to be found. Returns as soon as a message matching the specified search criteria is found. **Recommended:** This is the most efficient method of looking up a message, therefore we recommend using it wherever possible. ```go params := &mailosaur.MessageSearchParams { Server: "SERVER_ID", } criteria := &mailosaur.SearchCriteria { SentTo: "something@{SERVER_ID}.mailosaur.net", } message, err := m.Messages.Get(params, criteria) ``` To learn about inbox IDs, and what to replace `SERVER_ID` with, see [sending email to Mailosaur](/docs/email-testing/sending-to-mailosaur). ##### Parameters In addition to the inbox, you can also set the following… | PARAMETER | DESCRIPTION | | ------------ | ------------ | | **Server** | The unique identifier for your Mailosaur inbox. | | **Timeout** | Specify how long to wait for a matching result (in seconds, _default value is 10 seconds_). | | **ReceivedAfter** | Limits results to only messages received after this date/time (_default 1 hour ago_). | ##### Criteria | PARAMETER | DESCRIPTION | | ------------ | ------------ | | **SentFrom** | The full email address from which the target message was sent. | | **SentTo** | The full email address to which the target message was sent. | | **Subject** | The subject line of the target email. | | **Body** | Search for part of the message body. | | **Match** | If set to `ALL` (default), then only results that match all specified criteria will be returned. If set to `ANY`, results that match any of the specified criteria will be returned. | ```go // Search all messages received after midnight on a specific date params := &mailosaur.MessageSearchParams { Server: "SERVER_ID", ReceivedAfter: time.Date(2020, 1, 5, 0, 0, 0, 0, time.UTC), } criteria := &mailosaur.SearchCriteria { SentTo: "something@{SERVER_ID}.mailosaur.net", } message, err := m.Messages.Get(params, criteria) ``` #### Messages.List(params) Returns a list of your messages in summary form. The summaries are returned sorted by received date, with the most recently-received messages appearing first. > [!SUCCESS] > The method returns a message summary, rather than the full message object. This means that several properties, like the message body, are not included. To get this data, you’ll need to call [`GetById`](#messagesgetbyidid). Alternatively, we recommend using the [`Get`](#messagesgetparams-criteria-options) method, which is a far more efficient approach. ```go // List the most recent messages params := &mailosaur.MessageListParams { Server: server } result, err := m.Messages.List(params) if (err != nil) { // Handle err } // Get the most recent message (the first one in the list) message = result.Items[0] fmt.Println("Subject: " + message.Subject) ``` ##### Parameters - **Server** The unique identifier for your Mailosaur inbox. - **ReceivedAfter** Allows you to customise how far back to look for messages. - **Page** Used alongside `ItemsPerPage` to paginate through results. This is zero-based, meaning `0` is the first page of results. - **ItemsPerPage** A limit on the number of results to be returned. This can be set between 1 to 1000, with the default being 50. - **Dir** Optionally limits results based on the direction (`Sent` or `Received`), with the default being `Received`. ```go // List all results received after midnight on a specific date // Limit results to the first 10 matches only. params := &mailosaur.MessageListParams { Server: server, ReceivedAfter: time.Date(2020, 1, 3, 0, 0, 0, 0, time.UTC), Page: 0, ItemsPerPage: 50, } result, err = m.Messages.List(params) ``` #### Messages.Search(params, criteria) Returns a list of messages matching the specified search criteria, in summary form. The messages are returned sorted by received date, with the most recently-received messages appearing first. > [!SUCCESS] > The method returns a message summary, rather than the full message object. This means that several properties, like the message body, are not included. To get this data, you’ll need to call [`GetById`](#messagesgetbyidid). Alternatively, we recommend using the [`Get`](#messagesgetparams-criteria-options) method, which is a far more efficient approach. ```go params := &mailosaur.MessageListParams { Server: server, } criteria := &mailosaur.SearchCriteria { SentTo: "someone@SERVER_ID.mailosaur.net", } result, err := m.Messages.Search(params, criteria) if (err != nil) { // Handle err } // Get the most recent match message := result.Items[0] fmt.Println("Subject: " + message.Subject) ``` ##### Parameters - **Server** The unique identifier for your Mailosaur inbox. - **Timeout** If provided, determines how long to wait for a matching result (provided in milliseconds). - **ErrorOnTimeout** When set to `false`, an error will not be thrown if timeout is reached (default: `true`). Note the data type is `*bool`, therefore you must set this using a variable (e.g. `f := false` followed by `params.ErrorOnTimeout = &f`) - **ReceivedAfter** Allows you to customise how far back to look for messages. - **Page** Used alongside `ItemsPerPage` to paginate through results. This is zero-based, meaning `0` is the first page of results. - **ItemsPerPage** A limit on the number of results to be returned. This can be set between 1 to 1000, with the default being 50. - **Dir** Optionally limits results based on the direction (`Sent` or `Received`), with the default being `Received`. ##### Criteria - **SentFrom** The full email address from which the target message was sent. - **SentTo** The full email address to which the target message was sent. - **Subject** The subject line of the target email. - **Body** Search for part of the message body. - **Match** If set to `ALL` (default), then only results that match all specified criteria will be returned. If set to `ANY`, results that match any of the specified criteria will be returned. ```go // Search for all messages sent to someone@SERVER_ID.mailosaur.net, // received after midnight on a specific date. Limit results to // the first 10 matches only. params := &mailosaur.MessageListParams { Server: server, Page: 0, ItemsPerPage: 10, ReceivedAfter: time.Date(2020, 1, 3, 0, 0, 0, 0, time.UTC), } criteria := &mailosaur.SearchCriteria { SentTo: "someone@SERVER_ID.mailosaur.net", } result, err := m.Messages.Search(params, criteria) ``` #### Messages.GetById(id) Retrieves the detail for a single email message. Must be used in conjunction with either [`List`](#messageslistparams) or [`Search`](#messagessearchparams-criteria) in order to get the unique identifier for the required message. **We always recommend using the** [`Get`](#messagesgetparams-criteria-options) **method instead**. ```go result, err = m.Messages.List(&mailosaur.MessageListParams { Server: server, }) if (err != nil) { // Handle err } messageId := result.Items[0].Id message := m.Messages.GetById(messageId) fmt.Println("Subject: " + message.Subject) ``` #### Messages.Delete(id) Permanently deletes a message. Also deletes any attachments related to the message. This operation cannot be undone. ```go m.Messages.Delete(messageId) ``` #### Messages.DeleteAll(server) Permanently deletes all messages held in the specified inbox. Also deletes any attachments related to each message. This operation cannot be undone. ```go m.Messages.DeleteAll("SERVER_ID") ``` #### Messages.Create(server, messageCreateOptions) Creates a new message that can be sent to a verified email address. This is useful in scenarios where you want an email to trigger a workflow in your product. ```go options := &mailosaur.MessageCreateOptions { To: "verified-address@example.com", Send: true, Subject: "Request", Text: "Please can you give us a call back?", } m.Messages.Create("SERVER_ID", options) ``` ##### Options - **To** The email address to which the email will be sent. Must be a verified email address. - **Send** If true, email will be sent upon creation. - **Subject** The email subject line. - **Text** The plain text body of the email. - **Html** The HTML body of the email. #### Messages.Forward(messageId, messageForwardOptions) Forwards the specified email to a verified email address. ```go options := &mailosaur.MessageForwardOptions { To: "verified-address@example.com", Text: "FYI", } m.Messages.Forward("MESSAGE_ID", options) ``` ##### Options - **To** The email address to which the email will be sent. Must be a verified email address. - **Text** Any additional plain text content to forward the email with. - **Html** Any additional HTML content to forward the email with. #### Messages.Reply(messageId, messageReplyOptions) Sends a reply to the specified email. This is useful for when simulating a user replying to one of your emails. ```go options := &mailosaur.MessageReplyOptions { Text: "FYI", } m.Messages.Reply("MESSAGE_ID", options) ``` ##### Options - **Text** Any additional plain text content to include in the reply. - **Html** Any additional HTML content to include in the reply. ### Servers Inboxes capture emails and SMS messages, group your tests and settings, and manage access for your team. #### Servers.List() Returns a list of your inboxes. Inboxes are returned sorted in alphabetical order. ```go result, err := m.Servers.List() if (err != nil) { // Handle err } fmt.Println("You have an inbox called: " + result.Items[0].Name) ``` #### Servers.Create(options) Creates a new inbox. Only the `name` property is required to create a new inbox via the API. ```go options := &mailosaur.ServerCreateOptions { Name: "My email tests", } m.Servers.Create(options) ``` #### Servers.Get(id) Retrieves the detail for a single inbox. Simply supply the unique identifier for the required inbox. ```go server, err := m.Servers.Get("SERVER_ID") ``` #### Servers.GetPassword(id) Retrieves the password, for use with SMTP and POP3, for a single inbox. Simply supply the unique identifier for the required inbox. ```go password, err := m.Servers.GetPassword("SERVER_ID") ``` #### Servers.Update(id, server) Updates a single inbox. ```go retrievedServer, err := m.Servers.Get("SERVER_ID") if (err != nil) { // Handle err } retrievedServer.Name = "Updated inbox name" m.Servers.Update(retrievedServer.Id, retrievedServer); ``` #### Servers.Delete(id) Permanently deletes an inbox. Also deletes all messages and associated attachments within the inbox. This operation cannot be undone. ```go m.Servers.Delete("SERVER_ID") ``` #### Servers.GenerateEmailAddress(id) Utility method to help you generate a random email address for a given inbox. ```go emailAddress := m.Servers.GenerateEmailAddress("SERVER_ID") fmt.Println(emailAddress) // "bgwqj@SERVER_ID.mailosaur.net" ``` To learn about inbox IDs, and what to replace `SERVER_ID` with, see [sending email to Mailosaur](/docs/email-testing/sending-to-mailosaur). ### Files #### Files.GetEmail(messageId) Downloads an EML file representing the specified email. Simply supply the unique identifier for the required email. #### Files.GetAttachment(attachmentId) Downloads a single attachment. Simply supply the unique identifier for the required attachment. ### Analysis #### Analysis.Spam(messageId) Perform spam testing on the specified email. ### Usage #### Usage.Limits() Retrieve account usage limits. Details the current limits and usage for your account. This endpoint requires authentication with an account-level API key. #### Usage.Transactions() Retrieves the last 31 days of transactional usage. This endpoint requires authentication with an account-level API key. --- Source: https://mailosaur.com/docs/automation/html-content # HTML content of an email > [!WARNING] > Most email sent today is HTML-based, however, an email may also contain a plain text alternative for older mail clients. Learn how to work with text content of an email. ## Before you begin The examples shown below are based on two key assumptions: 1. You have already created a basic automated test using our [getting started guides](/docs/automation). 2. You have a chosen assertion library that you will use to test the values shown below. ## Accessing the HTML content An email’s HTML body can be accessed via the `html.body` property of a message. ```nodejs console.log(message.html.body) // "html->body); // "542163