2019-11-18 05:58:33 +01:00
---
2014-10-17 06:53:52 +02:00
title: How to test emails within unit tests
2019-11-18 05:58:33 +01:00
summary: Test email functionality without ever hitting an inbox
icon: envelope
---
2014-10-17 06:53:52 +02:00
# Testing Email within Unit Tests
2017-07-03 03:22:12 +02:00
SilverStripe's test system has built-in support for testing emails sent using the [Email ](api:SilverStripe\Control\Email\Email ) class. If you are
running a [SapphireTest ](api:SilverStripe\Dev\SapphireTest ) test, then it holds off actually sending the email, and instead lets you assert that an
2014-10-17 06:53:52 +02:00
email was sent using this method.
2017-08-03 02:51:32 +02:00
```php
2017-10-27 04:38:27 +02:00
use SilverStripe\Control\Email\Email;
public function MyMethod()
{
$e = new Email();
$e->To = "someone@example.com";
$e->Subject = "Hi there";
$e->Body = "I just really wanted to email you and say hi.";
$e->send();
}
2017-08-03 02:51:32 +02:00
```
2014-10-17 06:53:52 +02:00
2017-07-03 03:22:12 +02:00
To test that `MyMethod` sends the correct email, use the [SapphireTest::assertEmailSent() ](api:SilverStripe\Dev\SapphireTest::assertEmailSent( )) method.
2014-10-17 06:53:52 +02:00
2017-08-03 02:51:32 +02:00
```php
2017-10-27 04:38:27 +02:00
$this->assertEmailSent($to, $from, $subject, $body);
2014-10-17 06:53:52 +02:00
2017-10-27 04:38:27 +02:00
// to assert that the email is sent to the correct person
$this->assertEmailSent("someone@example.com", null, "/th.*e$/");
2017-08-03 02:51:32 +02:00
```
2014-10-17 06:53:52 +02:00
Each of the arguments (`$to`, `$from` , `$subject` and `$body` ) can be either one of the following.
* A string: match exactly that string
* `null/false` : match anything
* A PERL regular expression (starting with '/')
## Related Documentation
* [Email ](../../email )
## API Documentation
2017-07-03 03:22:12 +02:00
* [Email ](api:SilverStripe\Control\Email\Email )
2014-10-17 06:53:52 +02:00