0

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' => \Magento\Framework\App\Area::AREA_FRONTEND,
                    'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID,
                ]
            )
            ->setTemplateVars($templateVars)
            ->setFrom($sender)
            ->addTo($customerEmail);
        $logger->info('Email transport built successfully.');

        // Create the MIME part for the attachment
        $attachmentPart = new \Laminas\Mime\Part($fileContents);
        $attachmentPart->type = \Laminas\Mime\Mime::TYPE_OCTETSTREAM;
        $attachmentPart->disposition = \Laminas\Mime\Mime::DISPOSITION_ATTACHMENT;
        $attachmentPart->encoding = \Laminas\Mime\Mime::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 \Laminas\Mime\Message();
            $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 \Laminas\Mime\Message();
        $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.
New contributor
indian community is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
1
  • 1
    This question is similar to: Unable to add attachment as PDF. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Sep 4 at 17:26

1 Answer 1

0

I had a similar problem. I solved it in my 2.4.6.-5 like this.

I added:

use Magento\Framework\Mail\Template\TransportBuilderFactory;
use Laminas\Mime\Message as MimeMessage;
use Laminas\Mime\Mime as MimeType;
use Laminas\Mime\Part as MimePart;

Created the transport 

 $transportBuilder = $this->transportBuilderFactory->create();
            $transportBuilder
                ->setTemplateIdentifier('template_id')
                ->setTemplateOptions([
                    'area' => Area::AREA_FRONTEND,
                    'store' => Store::DEFAULT_STORE_ID,
                ])
                ->setTemplateVars(['body' => $body])
                ->setFrom(['email' => 'email', 'name' => 'title'])  // Corretto formato del mittente
                ->addTo('email');
            $transport = $transportBuilder->getTransport();$body = $transport->getMessage()->getBody();
            if ($body instanceof MimeMessage) {
                $parts = $body->getParts();

                $attachmentPart = new MimePart();
                $attachmentPart->setContent($fileContent)
                    ->setType($fileType)
                    ->setFileName($fileName)
                    ->setDisposition(MimeType::DISPOSITION_ATTACHMENT)
                    ->setEncoding(MimeType::ENCODING_BASE64);
                $parts[] = $attachmentPart;

                $message = new MimeMessage();
                $message->setParts($parts);

                $transport->getMessage()->setBody($message);
            }

            $transport->sendMessage();

I get my attached file.

New contributor
Andrea Mastracchio is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.