I have a custom contact form for sending emails. One of the options is to attach a PDF.

This is the part of the controller that handles checking the attachments and uploading them.

    $files = $this->getRequest()->getFiles();

        if ($files['attachments'] && $files['attachments']['size'] > 0) {
            if ($files['attachments']['size'] > self::ATTACHMENT_SIZE_LIMIT) {
                $this->messageManager->addErrorMessage(__('File size too large.'));
                return $this->_redirect('*/*/');
            try {
                $uploader = $this->fileUploaderFactory->create(['fileId' => 'attachments']);

            // write to the TMP directory since we don't need the file once it's emailed

                $directory = $this->fileSystem->getDirectoryWrite(DirectoryList::TMP);

                $filePath = $directory->getAbsolutePath('contact-attachments');

                $result = $uploader->save($filePath);
                $resultName = $uploader->getUploadedFileName();

                $attachmentPath = $result['path'] . $result['file'];
                $attachmentName = $resultName;

            } catch (\Exception $e) {
                $this->messageManager->addErrorMessage(__('File format not supported.'));
                return $this->_redirect('*/*/');
        } else {
            $attachmentPath = '';
            $attachmentName = '';

Is there any benefit to doing this vs. something simple like:

$attachmentPath = $files['attachments']['tmp_name'];
$attachmentName = $files['attachments']['name'];

With the necessary validations for type and size limit? Am I overthinking this? Both work, I'm just wondering if injecting the Filesystem and Uploader Factory is really necessary.

The transport builder is extended by using the Zend Framework createAttachment function, which for whatever reason is not included in Magento 2's base TransportBuilder.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.