I managed to get it working in my extension
https://github.com/DominicWatts/ContactAttachment
I based this off another tutorial. Sorry I can't find link.
public function send($replyTo, array $variables)
{
$filePath = null;
$fileName = null;
$uploaded = false;
try {
$fileCheck = $this->fileUploaderFactory->create(['fileId' => 'attachment']);
$file = $fileCheck->validateFile();
$attachment = $file['name'] ?? null;
} catch (\Exception $e) {
$attachment = null;
}
if ($attachment) {
$upload = $this->fileUploaderFactory->create(['fileId' => 'attachment']);
$upload->setAllowRenameFiles(true);
$upload->setFilesDispersion(true);
$upload->setAllowCreateFolders(true);
$upload->setAllowedExtensions(['txt', 'csv', 'jpg', 'jpeg', 'gif', 'png', 'pdf', 'doc', 'docx']);
$path = $this->fileSystem
->getDirectoryRead(DirectoryList::MEDIA)
->getAbsolutePath(self::FOLDER_LOCATION);
$result = $upload->save($path);
$uploaded = self::FOLDER_LOCATION . $upload->getUploadedFilename();
$filePath = $result['path'] . $result['file'];
$fileName = $result['name'];
}
/** @see \Magento\Contact\Controller\Index\Post::validatedParams() */
$replyToName = !empty($variables['data']['name']) ? $variables['data']['name'] : null;
$this->inlineTranslation->suspend();
$storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
$transport = $this->transportBuilder
->setTemplateIdentifier($this->contactsConfig->emailTemplate())
->setTemplateOptions(
[
'area' => Area::AREA_FRONTEND,
'store' => $this->storeManager->getStore()->getId(),
]
)
->setTemplateVars($variables)
->setFrom($this->contactsConfig->emailSender())
->addTo($this->contactsConfig->emailRecipient())
->setReplyTo($replyTo, $replyToName)
->getTransport();
if ($uploaded && !empty($filePath) && $this->file->fileExists($filePath)) {
$mimeType = mime_content_type($filePath);
$transport = $this->transportBuilder
->setTemplateIdentifier($this->contactsConfig->emailTemplate())
->setTemplateOptions(
[
'area' => Area::AREA_FRONTEND,
'store' => $this->storeManager->getStore()->getId(),
]
)
->addAttachment($this->file->read($filePath), $fileName, $mimeType)
->setTemplateVars($variables)
->setFrom($this->contactsConfig->emailSender())
->addTo($this->contactsConfig->emailRecipient())
->setReplyTo($replyTo, $replyToName)
->getTransport();
}
$transport->sendMessage();
$this->inlineTranslation->resume();
}