0

I have installed https://github.com/manishjoy1993/email-attachment extesnion in my magento 2.2.8 version. Everthing is fine but I can not send multiple attachment in single mail. For multiple attachments I have created 2 functions in controller

->addAttachment(self::TEST_FILE_CONTENT, self::TEST_FILE_NAME, self::TEST_FILE_TYPE)
->addAttachment1(self::TEST_FILE_CONTENT, self::TEST_FILE_NAME, self::TEST_FILE_TYPE)

If I pass only one addAttachment() function,so I am receiving pdf file perfectly if I attach 2 pdf file in two different function so I am getting this kind of mail enter image description here

here is my code in Controller file

<?php


namespace Excellence\EmailAttachment\Controller\Index;

use Excellence\EmailAttachment\Mail\Template\TransportBuilder;
use Magento\Framework\App\Area;
use Magento\Framework\App\State;
use Magento\Framework\Exception\MailException;

class Index extends \Magento\Framework\App\Action\Action
{
    /**@#+
     * Test Data.
     */
    const TEST_TEMPLATE_IDENTIFIER = 'excellence_test_attachment';
    const TEST_FROM_EMAIL = 'general';
    const TEST_TO_EMAIL = 'to@gmail.com';
    const TEST_FILE_CONTENT = 'Test file content.';
    const TEST_FILE_NAME = 'test12.pdf';
    const TEST_FILE_TYPE = 'application/pdf';
    /**@#-*/

    /**
     * @var \Excellence\EmailAttachment\Mail\Template\TransportBuilder
     */
    protected $transportBuilder;

    /**
     * @var \Magento\Framework\App\State
     */
    protected $state;

    /**
     * TestAttachment constructor.
     *
     * @param \Excellence\EmailAttachment\Mail\Template\TransportBuilder $transportBuilder
     * @param \Magento\Framework\App\State $state
     * @param null $name
     */

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        TransportBuilder $transportBuilder, State $state)
    {
        $this->transportBuilder = $transportBuilder;
        $this->state = $state;
        return parent::__construct($context);
    }

    public function execute()
    {
        try {
            // $this->state->setAreaCode(Area::AREA_FRONTEND);
            $sender = [
                                    'email' => 'aaaa@gmail.com',
                                    'name' => 'aaaaa'

                                ];
            $this->transportBuilder
                ->setTemplateIdentifier(self::TEST_TEMPLATE_IDENTIFIER)
                ->setTemplateOptions([
                                        'area' => 'frontend',
                                        'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID,
                                    ])
                ->setTemplateVars([])
                ->addAttachment(self::TEST_FILE_CONTENT, self::TEST_FILE_NAME, self::TEST_FILE_TYPE)
                ->addAttachment1(self::TEST_FILE_CONTENT, self::TEST_FILE_NAME, self::TEST_FILE_TYPE)
                ->setFrom($sender )
                ->addTo(self::TEST_TO_EMAIL)
                ->getTransport()
                ->sendMessage();

            print_r(__('Everything is fine, email has been sent.'));
        } catch (MailException $me) {
            print_r(__('MailException: %1', $me->getMessage()));
        } catch (\Exception $e) {
            print_r(__('Exception: %1', $e->getMessage()));
        }
    } 
}

Here is app\code\Excellence\EmailAttachment\Mail\Template\TransportBuilder.php file

<?php

namespace Excellence\EmailAttachment\Mail\Template;

class TransportBuilder extends \Magento\Framework\Mail\Template\TransportBuilder
{

    public function addAttachment($content, $fileName, $fileType)
    {
        $this->message->setBodyAttachment($content, $fileName, $fileType);

        return $this;
    }
    public function addAttachment1($content, $fileName, $fileType)
    {
        $this->message->setBodyAttachment($content, $fileName, $fileType);

        return $this;
    }

   protected function prepareMessage()
    {
        parent::prepareMessage();

        $this->message->setPartsToBody();

        return $this;
    }
}

app\code\Excellence\EmailAttachment\Mail\Message.php file

<?php


namespace Excellence\EmailAttachment\Mail;

use Zend\Mime\Mime;
use Zend\Mime\PartFactory;
use Zend\Mail\MessageFactory as MailMessageFactory;
use Zend\Mime\MessageFactory as MimeMessageFactory;

class Message extends \Magento\Framework\Mail\Message implements \Magento\Framework\Mail\MailMessageInterface
{
    /**
     * @var \Zend\Mime\PartFactory
     */
    protected $partFactory;

    /**
     * @var \Zend\Mime\MessageFactory
     */
    protected $mimeMessageFactory;

    /**
     * @var \Zend\Mail\Message
     */
    private $zendMessage;

    /**
     * @var \Zend\Mime\Part[]
     */
    protected $parts = [];


    public function __construct(PartFactory $partFactory, MimeMessageFactory $mimeMessageFactory, $charset = 'utf-8')
    {
        $this->partFactory = $partFactory;
        $this->mimeMessageFactory = $mimeMessageFactory;
        $this->zendMessage = MailMessageFactory::getInstance();
        $this->zendMessage->setEncoding($charset);
    }

    public function setBodyText($content)
    {
        $textPart = $this->partFactory->create();

        $textPart->setContent($content)
            ->setType(Mime::TYPE_TEXT)
            ->setCharset($this->zendMessage->getEncoding());

        $this->parts[] = $textPart;

        return $this;
    }

    public function setBodyHtml($content)
    {
        $htmlPart = $this->partFactory->create();

        $htmlPart->setContent($content)
            ->setType(Mime::TYPE_HTML)
            ->setCharset($this->zendMessage->getEncoding());

        $this->parts[] = $htmlPart;

        return $this;
    }


    public function setBodyAttachment($content, $fileName, $fileType)
    {
        $attachmentPart = $this->partFactory->create();

        $attachmentPart->setContent($content)
            ->setType($fileType)
            ->setFileName($fileName)
            ->setDisposition(Mime::DISPOSITION_ATTACHMENT)
            ->setEncoding(Mime::ENCODING_BASE64);

        $this->parts[] = $attachmentPart;

        return $this;
    }


    public function setPartsToBody()
    {
        $mimeMessage = $this->mimeMessageFactory->create();
        $mimeMessage->setParts($this->parts);
        $this->zendMessage->setBody($mimeMessage);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function setBody($body)
    {
        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function setSubject($subject)
    {
        $this->zendMessage->setSubject($subject);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getSubject()
    {
        return $this->zendMessage->getSubject();
    }

    /**
     * {@inheritdoc}
     */
    public function getBody()
    {
        return $this->zendMessage->getBody();
    }

    /**
     * {@inheritdoc}
     */
    public function setFrom($fromAddress)
    {
        $this->zendMessage->setFrom($fromAddress);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function addTo($toAddress)
    {
        $this->zendMessage->addTo($toAddress);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function addCc($ccAddress)
    {
        $this->zendMessage->addCc($ccAddress);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function addBcc($bccAddress)
    {
        $this->zendMessage->addBcc($bccAddress);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function setReplyTo($replyToAddress)
    {
        $this->zendMessage->setReplyTo($replyToAddress);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getRawMessage()
    {
        return $this->zendMessage->toString();
    }

    /**
     * @inheritDoc
     */
    public function setMessageType($type)
    {
        return $this;
    }
}
0

Hi bro try like this..

TransportBuilder

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

use Magento\Framework\Mail\MessageInterface;
use Magento\Framework\Mail\MessageInterfaceFactory;
use Magento\Framework\Mail\Template\FactoryInterface;
use Magento\Framework\Mail\Template\SenderResolverInterface;
use Magento\Framework\Mail\TransportInterfaceFactory;
use Magento\Framework\ObjectManagerInterface;
use Zend\Mime\Mime;
use Zend\Mime\Part as MimePart;
use Zend\Mime\PartFactory as MimePartFactory;
use Zend\Mime\Message as MimeMessage;
use Zend\Mime\MessageFactory as MimeMessageFactory;

class TransportBuilder extends \Magento\Framework\Mail\Template\TransportBuilder
{
/** @var MimePart[] */
private $parts = [];

/** @var MimeMessageFactory */
private $mimeMessageFactory;

/** @var MimePartFactory */
private $mimePartFactory;

public function __construct(
    FactoryInterface $templateFactory,
    MessageInterface $message,
    SenderResolverInterface $senderResolver,
    ObjectManagerInterface $objectManager,
    TransportInterfaceFactory $mailTransportFactory,
    MimePartFactory $mimePartFactory,
    MimeMessageFactory $mimeMessageFactory,
    MessageInterfaceFactory $messageFactory = null
) {
    parent::__construct(
        $templateFactory,
        $message,
        $senderResolver,
        $objectManager,
        $mailTransportFactory,
        $messageFactory
    );

    $this->mimePartFactory    = $mimePartFactory;
    $this->mimeMessageFactory = $mimeMessageFactory;
}

protected function prepareMessage()
{
    parent::prepareMessage();

    $mimeMessage = $this->getMimeMessage($this->message);

    foreach ($this->parts as $part) {
        $mimeMessage->addPart($part);
    }

    $this->message->setBody($mimeMessage);

    return $this;
}

public function addAttachment(
    $filename = null,
    $body,
    $mimeType = Mime::TYPE_OCTETSTREAM,
    $disposition = Mime::DISPOSITION_ATTACHMENT,
    $encoding = Mime::ENCODING_BASE64
) {
    $this->parts[] = $this->createMimePart($filename, $body, $mimeType, $disposition, $encoding);
    return $this;
}

private function createMimePart(
    $filename = null,
    $content,
    $type = Mime::TYPE_OCTETSTREAM,
    $disposition = Mime::DISPOSITION_ATTACHMENT,
    $encoding = Mime::ENCODING_BASE64
) {
    /** @var MimePart $mimePart */
    $mimePart = $this->mimePartFactory->create(['content' => $content]);
    $mimePart->setType($type);
    $mimePart->setDisposition($disposition);
    $mimePart->setEncoding($encoding);

    if ($filename) {
        $mimePart->setFileName($filename);
    }

    return $mimePart;
}

private function getMimeMessage(MessageInterface $message)
{
    $body = $message->getBody();

    if ($body instanceof MimeMessage) {
        return $body;
    }

    /** @var MimeMessage $mimeMessage */
    $mimeMessage = $this->mimeMessageFactory->create();

    if ($body) {
        $mimePart = $this->createMimePart((string)$body, Mime::TYPE_TEXT, Mime::DISPOSITION_INLINE);
        $mimeMessage->setParts([$mimePart]);
    }

    return $mimeMessage;
}

Create a preference for Magento\Framework\Mail\Template\TransportBuilder.php and than test in your custom controller with the multiple addAttachment() method. It should work. It worked for me.

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.