Mailosaur logo
Mailosaur logo

How to test email and SMS in PHP

Learn how to automate test email and SMS messages in PHP, using Mailosaur.

1. Create a Mailosaur account
A hashtag icon

If you already have an account, skip to step 2.

To create a new trial account, sign up here.

2. Create a sample project
A hashtag icon

Install PHP
A hashtag icon

To see if you already have PHP installed, open a terminal window and run this command:

php --version

If PHP is installed, you’ll see a version number. If you see an error instead, then download PHP and install it.

Create a new project
A hashtag icon

Run each of these commands to create a new folder for your PHP project:

mkdir EmailTests
cd EmailTests

Install the Mailosaur PHP library
A hashtag icon

Run this command to install the Mailosaur PHP package:

composer require mailosaur/mailosaur

If you don’t have composer installed, download and install it here.

3. Send email to your Mailosaur server
A hashtag icon

Servers allow you to group tests, permissions, and other settings together. Each server has a Server ID, 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 to use. You can learn more about creating API keys here.

Retrieve your server’s attributes
A hashtag icon

  1. Go to the Servers page in the Mailosaur Dashboard.
  2. Click on the name of the server you want to test with.
  3. Click on the API tab.
  4. Make a note of the Server ID, domain name and API key.

Send an email to your server
A hashtag icon

If the domain name of your server above was:

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. Go to the Servers page in the Mailosaur Dashboard.
  3. Click on the name of the server 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.

4. Find an email for automated testing
A hashtag icon

Now that you have a sample project, your server’s credentials, and an email to test, then you’re ready to continue.

Create a file named hello.php and type or paste in this code sample, replacing the template code with the values from step 3 above:

<?php

require_once('vendor/autoload.php');

use Mailosaur\MailosaurClient;
use Mailosaur\Models\SearchCriteria;

// Available in the API tab of a server
$apiKey = 'YOUR_API_KEY';
$serverId = 'SERVER_ID';
$serverDomain = 'SERVER_DOMAIN';

$mailosaur = new MailosaurClient($apiKey);

$criteria = new SearchCriteria();
$criteria->sentTo = 'anything@' . $serverDomain;

$email = $mailosaur->messages->get($serverId, $criteria);

print('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:

php hello.php

If everything is set up correctly, you should see the subject line of the last email you sent, printed to screen:

Subject: My example email

Troubleshooting
A hashtag icon

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 received_after option (see library reference below).

5. Narrowing your search results
A hashtag icon

Only find messages received after a certain time
A hashtag icon

By default, searches include messages received in the last hour, but you can customise the search window with the received_after option.

This example shows you how to only include emails received after your test started:

$testStart = new \DateTime();

// Perform the steps that send a message here

$criteria = new SearchCriteria();
$criteria->sentTo = '...';

$message = $mailosaur->messages->get(
  '...',
  $criteria,
  10000, // Wait for up to 10 seconds
  $testStart
);

Search criteria
A hashtag icon

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 this criteria too:

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
A hashtag icon

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:

SMS Testing
A hashtag icon

You can test SMS messages in much the same way as email. Take a look at our guide on testing SMS messages for more information.

Library reference
A hashtag icon

The PHP client library gives you access to several other methods.

Messages
A hashtag icon

Messages is the collective name given to the email and/or SMS messages that are sent into Mailosaur for testing. The message object contains everything you need to perform in-depth automated testing.

messages->get(server, criteria, timeout, receivedAfter)
A hashtag icon

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.

$criteria = new SearchCriteria();
$criteria->sentTo = 'someone@SERVER_ID.mailosaur.net';

$message = $mailosaur->messages->get('SERVER_ID', $criteria);

To learn about Server IDs, and what to replace SERVER_ID with, see sending email to Mailosaur.

Criteria
A hashtag icon
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
A hashtag icon
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).
$criteria = new SearchCriteria();
$criteria->sentTo = 'someone@SERVER_ID.mailosaur.net';

$tenMinutesAgo = new \DateTime();
$tenMinutesAgo->sub(new \DateInterval('PT10M'));

# Search all messages received in the last 10 minutes (with 10s timeout)
$message = $mailosaur->messages->get('SERVER_ID', $criteria, 10000, $tenMinutesAgo);

messages->all(server, page, itemsPerPage, receivedAfter)
A hashtag icon

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.

Message summaries 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. Alternatively, we recommend using the get method, which is a far more efficient approach.

# List the most recent messages
$result = $mailosaur->messages->all('SERVER_ID');

# Get the most recent message (the first one in the list)
$message = $result->items[0];

print('Subject: ' . $message->subject);
Options
A hashtag icon
  • 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.
$tenMinutesAgo = new \DateTime();
$tenMinutesAgo->sub(new \DateInterval('PT10M'));

# List all results received in the last 10 minutes.
# Limit results to the first 10 matches only.
$result = $mailosaur->messages->all('SERVER_ID', 0, 10, $tenMinutesAgo);

messages->search(server, criteria, page, itemsPerPage, timeout, receivedAfter)
A hashtag icon

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.

Message summaries 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. Alternatively, we recommend using the get method, which is a far more efficient approach.

$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);
Criteria
A hashtag icon
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
A hashtag icon
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 throw 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.
$criteria = new SearchCriteria();
$criteria->sentTo = 'someone@SERVER_ID.mailosaur.net';

# Search for all messages sent to someone@SERVER_ID.mailosaur.net,
# received in the last 2 hours. Limit results to the first 10 matches only.
$twoHoursAgo = new \DateTime();
$twoHoursAgo->sub(new \DateInterval('PT2H'));

$result = $mailosaur->messages->search('SERVER_ID', $criteria, 0, 10, null, $twoHoursAgo);

messages->getById(id)
A hashtag icon

Retrieves the detail for a single email message. Must be used in conjunction with either all or search in order to get the unique identifier for the required message. We always recommend using the get method instead.

$result = $mailosaur->messages->all('SERVER_ID');
$messageId = $result->items[0]->id;

$message = $mailosaur->messages->getById($messageId);

print('Subject: ' . $message->subject);

messages->delete(id)
A hashtag icon

Permanently deletes a message. Also deletes any attachments related to the message. This operation cannot be undone.

$mailosaur->messages->delete($messageId);

messages->deleteAll(server)
A hashtag icon

Permanently deletes all messages held by the specified server. Also deletes any attachments related to each message. This operation cannot be undone.

$mailosaur->messages->deleteAll('SERVER_ID');

messages->create(server, messageCreateOptions)
A hashtag icon

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.

$options = new MessageCreateOptions();
$options->to = 'verified-address@example.com';
$options->send = TRUE;
$options->subject = 'Request';
$options->text = 'Please can you give us a call back?';

$mailosaur->messages->create('SERVER_ID', $options);
Options
A hashtag icon
  • 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)
A hashtag icon

Forwards the specified email to a verified email address.

$options = new MessageForwardOptions();
$options->to = 'verified-address@example.com';
$options->text = 'FYI';

$mailosaur->messages->forward('MESSAGE_ID', $options);
Options
A hashtag icon
  • to The email address to which the email will be sent. Must be a verified email address.
  • text Any additional HTML content to forward the email with.
  • html Any additional plain text content to forward the email with.

messages->reply(messageId, messageReplyOptions)
A hashtag icon

Sends a reply to the specified email. This is useful for when simulating a user replying to one of your emails.

$options = new MessageReplyOptions();
$options->text = 'FYI';

$mailosaur->messages->reply('MESSAGE_ID', $options);
Options
A hashtag icon
  • text Any additional plain text content to include in the reply.
  • html Any additional HTML content to include in the reply.

Servers
A hashtag icon

Servers contain all the configuration and set up for.

servers->all()
A hashtag icon

Returns a list of your virtual servers. Servers are returned sorted in alphabetical order.

$result = $mailosaur->servers->all();

print('You have a server called: ' . $result->items[0]->name);

servers->create(server)
A hashtag icon

Creates a new virtual server. Only the name property is required to create a new server via the API.

$createOptions = new ServerCreateOptions('My email tests');
$mailosaur->servers->create($createOptions);

servers->get(id)
A hashtag icon

Retrieves the detail for a single server. Simply supply the unique identifier for the required server.

$server = $mailosaur->servers->get('SERVER_ID');

servers->getPassword(id)
A hashtag icon

Retrieves the password, for use with SMTP and POP3, for a single server. Simply supply the unique identifier for the required server.

$password = $mailosaur->servers->getPassword('SERVER_ID');

servers->update(id, server)
A hashtag icon

Updates a single server.

$retrievedServer = $mailosaur->servers->get('SERVER_ID');
$retrievedServer->name = 'Updated server name';

$mailosaur->servers->update($retrievedServer->id, $retrievedServer);

servers->delete(id)
A hashtag icon

Permanently deletes a server. Also deletes all messages and associated attachments within the server. This operation cannot be undone.

$mailosaur->servers->delete('SERVER_ID');

servers.generate_email_address(id)
A hashtag icon

Utility method to help you generate a random email address for a given server.

$emailAddress = $mailosaur->servers->generateEmailAddress('SERVER_ID');

print($emailAddress); // "bgwqj@SERVER_ID.mailosaur.net"

To learn about Server IDs, and what to replace SERVER_ID with, see sending email to Mailosaur.

Files
A hashtag icon

files->getEmail(messageId)
A hashtag icon

Downloads an EML file representing the specified email. Simply supply the unique identifier for the required email.

files->getAttachment(attachmentId)
A hashtag icon

Downloads a single attachment. Simply supply the unique identifier for the required attachment.

Analysis
A hashtag icon

analysis->spam(messageId)
A hashtag icon

Perform spam testing on the specified email.

Usage
A hashtag icon

usage->limits()
A hashtag icon

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()
A hashtag icon

Retrieves the last 31 days of transactional usage. This endpoint requires authentication with an account-level API key.