protected function attachFiles()
{
if (count($this->attachments) === 0) {
return;
}
// Get old message parts
$mimeMessage = $this->message->getBody();
if (is_string($mimeMessage)) {
$originalBodyPart = new Mime\Part($mimeMessage);
$originalBodyPart->type = $mimeMessage != strip_tags($mimeMessage) ? Mime\Mime::TYPE_HTML : Mime\Mime::TYPE_TEXT;
// A Mime\Part body will be wraped into a Mime\Message, ensuring we handle a Mime\Message after this point
$this->setBody($originalBodyPart);
$mimeMessage = $this->message->getBody();
}
$oldParts = $mimeMessage->getParts();
// Generate a new Mime\Part for each attachment
$attachmentParts = [];
$info = new \finfo(FILEINFO_MIME_TYPE);
foreach ($this->attachments as $key => $attachment) {
if (!is_file($attachment)) {
continue;
// If checked file is not valid, continue to the next
}
// If the key is a string, use it as the attachment name
$basename = is_string($key) ? $key : basename($attachment);
$part = new Mime\Part(fopen($attachment, 'r'));
$part->id = $basename;
$part->filename = $basename;
$part->type = $info->file($attachment);
$part->encoding = Mime\Mime::ENCODING_BASE64;
$part->disposition = Mime\Mime::DISPOSITION_ATTACHMENT;
$attachmentParts[] = $part;
}
$body = new Mime\Message();
$body->setParts(array_merge($oldParts, $attachmentParts));
$this->message->setBody($body);
}