Skip to content

Unable to Add PDF to email in Magento2.4.6

I’m using Magento 2.4.6-p3 and have saved a PDF file in the pub/media/credit/ directory. The email is being sent correctly, but the attachment is not included when I check the email.

public function sendMail($customerEmail)
{
    $filePath = 'pub/media/credit/test.pdf';
    $writer = new Zend_Log_Writer_Stream(BP . '/var/log/storeManager.log');
    $logger = new Zend_Log();
    $logger->addWriter($writer);

    try {
        $logger->info('Starting email send process.');

        $this->inlineTranslation->suspend();
        $sender = [
            'name' => 'ProjectName',
            'email' => '[email protected]'
        ];

        // Read the file contents to attach
        if (file_exists($filePath)) {
            $fileContents = file_get_contents($filePath);
            $fileName = basename($filePath);
            $logger->info('File found and contents read successfully.');
        } else {
            $logger->err('File does not exist: ' . $filePath);
            throw new Exception('File not found: ' . $filePath);
        }

        $storeId = $this->getStoreId();
        $logger->info('Current Store ID: ' . $storeId);

        // Get templateId value from config
        $templateId = $this->scopeConfig->getValue(
            self::EMAIL_TEMPLATE,
            ScopeInterface::SCOPE_STORE,
            $storeId
        );
        $logger->info('Template ID retrieved: ' . $templateId);

        $templateVars = [
            'message_1' => 'CUSTOM MESSAGE STR 1',
            'message_2' => 'custom message str 2',
            'test_message' => 'This is a test message.',
            'store' => $this->getStore()
        ];

        // Build the email with the template and set template variables
        $this->transportBuilder
            ->setTemplateIdentifier($templateId)
            ->setTemplateOptions(
                [
                    'area' => MagentoFrameworkAppArea::AREA_FRONTEND,
                    'store' => MagentoStoreModelStore::DEFAULT_STORE_ID,
                ]
            )
            ->setTemplateVars($templateVars)
            ->setFrom($sender)
            ->addTo($customerEmail);
        $logger->info('Email transport built successfully.');

        // Create the MIME part for the attachment
        $attachmentPart = new LaminasMimePart($fileContents);
        $attachmentPart->type = LaminasMimeMime::TYPE_OCTETSTREAM;
        $attachmentPart->disposition = LaminasMimeMime::DISPOSITION_ATTACHMENT;
        $attachmentPart->encoding = LaminasMimeMime::ENCODING_BASE64;
        $attachmentPart->filename = $fileName;
        $logger->info('Attachment part created with filename: ' . $fileName);

        // Get the transport and the message object
        $transport = $this->transportBuilder->getTransport();
        $message = $transport->getMessage();
        $logger->info('Transport and message object retrieved.');

        // Check and create MIME message if it doesn't exist
        $existingBody = $message->getBody();
        if (!$existingBody) {
            $mimeMessage = new LaminasMimeMessage();
            $message->setBody($mimeMessage);
            $existingBody = $message->getBody();
            $logger->info('New MIME message created.');
        }

        // Get the existing body and append the attachment
        $mimeParts = $existingBody->getParts();
        $mimeParts[] = $attachmentPart;
        $logger->info('Attachment added to MIME parts.');

        // Create the MIME message with both parts
        $mimeMessage = new LaminasMimeMessage();
        $mimeMessage->setParts($mimeParts);
        $logger->info('MIME message set with attachment.');

        // Set the MIME message as the body of the email message
        $message->setBody($mimeMessage);
        $logger->info('MIME message body set.');

        // Send the email
        $transport->sendMessage();
        $logger->info('Email sent successfully.');

        $this->inlineTranslation->resume();
    } catch (Exception $e) {
        $logger->err('Error during email send: ' . $e->getMessage());
        $this->inlineTranslation->resume();
    }
}

/*
 * Get current store ID
 */
public function getStoreId()
{
    return $this->storeManager->getStore()->getId();
}

/*
 * Get current store info
 */
public function getStore()
{
    return $this->storeManager->getStore();
}

}

log

2024-09-04T12:00:16+00:00 INFO (6): Starting email send process.
2024-09-04T12:00:16+00:00 INFO (6): File found and contents read successfully.
2024-09-04T12:00:16+00:00 INFO (6): Current Store ID: 1
2024-09-04T12:00:16+00:00 INFO (6): Template ID retrieved: 16
2024-09-04T12:00:16+00:00 INFO (6): Email transport built successfully.
2024-09-04T12:00:16+00:00 INFO (6): Attachment part created with filename: test.pdf
2024-09-04T12:00:16+00:00 INFO (6): Transport and message object retrieved.
2024-09-04T12:00:16+00:00 INFO (6): New MIME message created.
2024-09-04T12:00:16+00:00 INFO (6): Attachment added to MIME parts.
2024-09-04T12:00:16+00:00 INFO (6): MIME message set with attachment.

2024-09-04T12:00:16+00:00 INFO (6): MIME message body set.
2024-09-04T12:00:20+00:00 INFO (6): Email sent successfully.