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.

We already know how to check if the email was sent or not but in this small method we're going to check if the email has attachments or not.


FeatureContext method


There is an example how to get all emails in this blog. Also the o:tag is what I use as a custom header when I send emails so it can be anything. There is an example about it as well.


/**
* @param string $tag
*
* @Then /^an email with o:tag "([^"]*)" should contain attachments with PNG and DOC extensions$/
*
* @throws BehaviorException
*/
public function anEmailWithOTagShouldContainAttachmentsWithPngAndDocExtensions($tag)
{
$extensions['png'] = null;
$extensions['doc'] = null;

$messages = $this->getAllSentMessages();
foreach ($messages as $message) {
$headers = $message->getHeaders();
if ($headers->has('o:tag')) {
/** @var Swift_Mime_Headers_UnstructuredHeader $oTagHeader */
$oTagHeader = $headers->get('o:tag');
$oTags = (array) $oTagHeader->getValue();
if (in_array($tag, $oTags)) {
foreach ($message->getChildren() as $child) {
$attachment = str_replace(
'attachment; filename=',
null,
$child->getHeaders()->get('content-disposition')->getFieldBody()
);

if (array_key_exists(pathinfo($attachment, PATHINFO_EXTENSION), $extensions)) {
unset($extensions[pathinfo($attachment, PATHINFO_EXTENSION)]);
}
}
}
}
}

if ($extensions) {
throw new BehaviorException('Attachment with relevant extensions cannot be found.');
}
}