# 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.