Magento 2.3 – How to Add Attachment with Email Using Zend Framework 2

attachmentemailmagento2.3pdfsales-order

I am working on a module in which I need to attach an attachment with sales email. However, Magento 2.3 use zendframework2 so email attachment is not the same as zendframework1 (in Magento 2.2).

Can anyone help me to achieve the same task? How to implement attachment functions in Magento 2.3

I have searched in google and read several questions but I didn't find the solution.

Best Answer

Fixed this issue by extending Magento\Framework\Mail\Message and adding new function createCustomAttachment in this, also edited the createHtmlMimeFromString function.

protected $attachment;

public function createCustomAttachment($body, $mimeType, $disposition, $encoding, $filename){
    $attachment = new Part($body);
    $attachment->setType($mimeType);
    $attachment->setDisposition($disposition);
    $attachment->setEncoding($encoding);
    $attachment->setFileName($filename);
    $this->attachment = $attachment;
    return $this;
}

Called the global variable $this->attachment in the function createHtmlMimeFromString. If the variable has value then we are adding the attachment data to the addPart function.

The code be like this

private function createHtmlMimeFromString($htmlBody)
{
    $htmlPart = new Part($htmlBody);
    $htmlPart->setCharset($this->zendMessage->getEncoding());
    $htmlPart->setType(Mime::TYPE_HTML);
    $mimeMessage = new \Zend\Mime\Message();
    $mimeMessage->addPart($htmlPart);
    if ($this->attachment) {
        $mimeMessage->addPart($this->attachment);
    }

    return $mimeMessage;
}

We need to copy the Magento\Framework\Mail\Message entire content in the extended file because the zendMessage is private and this is called in almost all functions.

We can call the createCustomAttachment function from the transport builder to pass the attachment details.

public function addAttachment($body,
                              $mimeType = Mime::TYPE_OCTETSTREAM,
                              $disposition = Mime::DISPOSITION_ATTACHMENT,
                              $encoding = Mime::ENCODING_BASE64,
                              $filename = null)
{
    //$this->message->createAttachment($body, $mimeType, $disposition, $encoding, $filename);
    $this->message->createCustomAttachment($body, $mimeType, $disposition, $encoding, $filename);
    return $this;
}
Related Topic