Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

You can use this example to test Swiftmailer. If you open symfony profiler and go to Email tab, you should see the actual email. For more info about email testing, visit here.


Config_test.yml


framework:
profiler:
collect: true

Sending email


Assign unique ID to emails with $uniqueId you're sending.


….......
$subject = 'Test message';
$body = 'Hi,
How are you?
Kind regards';
$uniqueId = '1234QWERTY';
….......
->setSubject($subject)
->setFrom($from)
->setTo($to)
->setBody($body);

$message->getHeaders()->addTextHeader('X-Message-ID', $uniqueId);
….......

Gherkin



Feature: Test

@mink:symfony2
Scenario: I can send email
Then I should get an email with ID "1234QWERTY" and subject "Test message" containing:
"""
Hi,
How are you?
Kind regards
"""

FeatureContext.php


If you're extending BehatContext then use $this->getMainContext()->getSession() otherwise use $this->getSession() for MinkContext.


use Behat\Gherkin\Node\PyStringNode;
use Behat\Mink\Exception\UnsupportedDriverActionException;
use Behat\Symfony2Extension\Driver\KernelDriver;
use RuntimeException;

class FeatureContext extends BehatContext implements KernelAwareInterface
{
/**
* @Given /^I should get an email with ID "([^"]*)" and subject "([^"]*)" containing:$/
*
* @param string $id
* @param string $subject
* @param PyStringNode $body
*
* @throws ErrorException
* @throws UnsupportedDriverActionException
*/
public function iShouldGetAnEmail($id, $subject, PyStringNode $body)
{
$profile = $this->getSymfonyProfile();
$collector = $profile->getCollector('swiftmailer');
$body = $body->getRaw();

foreach ($collector->getMessages() as $message) {
$headers = $message->getHeaders();
if (
$headers->has('X-Message-ID') &&
$headers->get('X-Message-ID')->getFieldBodyModel() == $id &&
$message->getSubject() == $subject &&
trim($message->getBody()) == $body
) {
return;
}
}

throw new ErrorException(sprintf('No message with ID "%s" sent.', $id));
}

private function getSymfonyProfile()
{
$driver = $this->getMainContext()->getSession()->getDriver();

if (!$driver instanceof KernelDriver) {
throw new UnsupportedDriverActionException(
'You need to tag the scenario with "@mink:symfony2". Using the profiler is not supported by %s.', $driver
);
}

$profile = $driver->getClient()->getProfile();

if (false === $profile) {
throw new RuntimeException(
'The profiler is disabled. Activate it by setting framework.profiler.collect to true in your config'
);
}

return $profile;
}
}