1

I sent a single file attachment. Now i need to send multiple attachment in single mail.Attachment will be in different format like .pdf,.jpeg,.png.

etc\di.xml

<preference for="\Magento\Framework\Mail\Template\TransportBuilder" type="\Vendor\Module\Magento\Mail\Template\TransportBuilder" />

and in my TransportBuilder.php file

 <?php
namespace Vendor\Module\Magento\Mail\Template;

class TransportBuilder extends \Magento\Framework\Mail\Template\TransportBuilder
{
    public function addAttachment($file, $name)
    {
        if (!empty($file) && file_exists($file)) {
            $this->message
                ->createAttachment(
                    file_get_contents($file),
                    \Zend_Mime::TYPE_OCTETSTREAM,
                    \Zend_Mime::DISPOSITION_ATTACHMENT,
                    \Zend_Mime::ENCODING_BASE64,
                    basename($name)
                );
        }
        return $this;
    }
}

and in my post.php

$from = ['email' => $fromEmail, 'name' => $fromName];
        $this->inlineTranslation->suspend();
        $templateOptions = [
            'area' => Area::AREA_FRONTEND,
            'store' => $this->storeManager->getStore()->getId()
        ];
        try {
            $transport = $this->transportBuilder->setTemplateIdentifier($template)
                ->setTemplateOptions($templateOptions)
                ->setTemplateVars(['data' => $postObject])
                ->setFrom($from)
                ->addTo($to)
                ->addAttachment($file, $name)
                ->getTransport();
            $transport->sendMessage();
            $this->inlineTranslation->resume();
        } catch (\Exception $e) {
            $this->helper->printLog($e->getMessage());
        }
2

I think adding multiple addAttachment function will work for you.

$transport = $this->transportBuilder->setTemplateIdentifier($template)
                ->setTemplateOptions($templateOptions)
                ->setTemplateVars(['data' => $postObject])
                ->setFrom($from)
                ->addTo($to)
                ->addAttachment($file, $name)
                ->addAttachment($file2, $name2)
                ->getTransport();

Because if you debug the code for Zend_Mail::addAttachment

public function addAttachment(Zend_Mime_Part $attachment)
{
    $this->addPart($attachment);
    $this->hasAttachments = true;

    return $this;
}

which uses Zend_Mime_Message::addPart() function.

public function addPart(Zend_Mime_Part $part)
{
    /**
     * @todo check for duplicate object handle
     */
    $this->_parts[] = $part;
}

Which generates array for the available parts. So, using addAttachment multiple times will only add more values to the $_parts array.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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