/**
* Get email data from file
*
* @param string $filename
* @throws Exception
* @return array
*/
protected function getEmailFromFile($filename)
{
$contents = file_get_contents($filename);
$email = array('to' => null, 'subject' => null, 'headers' => null, 'message' => null);
$headers = substr($contents, 0, strpos($contents, $this->message->getEol() . $this->message->getEol()));
$email['message'] = trim(str_replace($headers, '', $contents));
$email['headers'] = trim($headers) . $this->message->getEol() . $this->message->getEol();
if (strpos($email['headers'], 'Subject:') === false) {
throw new Exception("Error: There is no subject in the email file '" . $filename . "'.");
}
if (strpos($email['headers'], 'To:') === false) {
throw new Exception("Error: There is no recipient in the email file '" . $filename . "'.");
}
$subject = substr($contents, strpos($contents, 'Subject:'));
$subject = substr($subject, 0, strpos($subject, $this->message->getEol()));
$email['headers'] = str_replace($subject . $this->message->getEol(), '', $email['headers']);
$email['subject'] = trim(substr($subject . $this->message->getEol(), strpos($subject, ':') + 1));
$to = substr($contents, strpos($contents, 'To:'));
$to = substr($to, 0, strpos($to, $this->message->getEol()));
$email['headers'] = str_replace($to . $this->message->getEol(), '', $email['headers']);
preg_match('/[a-zA-Z0-9\\.\\-\\_+%]+@[a-zA-Z0-9\\-\\_\\.]+\\.[a-zA-Z]{2,4}/', $to, $result);
if (!isset($result[0])) {
throw new Exception("Error: An valid email could not be parsed from the email file '" . $filename . "'.");
} else {
$email['to'] = $result[0];
}
return $email;
}