1

I have custom form with add file button. Once user submit the form i need to sent form details with pdf in mail.

I tried different solutions.

and i follow this - Magento 2.4.2 How to attched PDF in Email?

but i got error like

1 exception(s):
Exception #0 (ReflectionException): Class Zend\Mime\PartFactory does not exist

so i used Laminas in place of zend then i face same error like

1 exception(s):
Exception #0 (ReflectionException): Class Laminas\Mime\PartFactory does not exist

Mani
  • 383
  • 2
  • 13

1 Answers1

0

Magento2.4 does not provide addattachment function in TransportBuilder Class, You need to build it.

 public function __construct(         
         ...
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \{{vendor}}\{{module}}\Model\Mail\Template\TransportBuilder $transportBuilder
{

    $this->_scopeConfig = $scopeConfig;
    $this->_transportBuilder = $transportBuilder;

    ....
}
public function execute()
{       
     $templateOptions = [
      'area' => \Magento\Framework\App\Area::AREA_FRONTEND,
      'store' => 1
    ];
    $templateVars = [
        'var1'      => 'value1',
        'var2'      => 'value2',
        'var3'      => 'value3',
        'var4'      => 'value4'
    ];
    $filePath = '/home/basic/Desktop/test.pdf';  //get your pdf file path
    $fileName = "filename.pdf";  //set your email attachment pdf name
    $fromEmail = "formemail@gmail.com"; //set from email
    $fromName = 'your name'; // set from name
    $fromdata = ['email' => $fromEmail, 'name' => $fromName];                
    $to =  $this->_scopeConfig->getValue(
        'contact/email/recipient_email',
        \Magento\Store\Model\ScopeInterface::SCOPE_STORE
    );                     
    $emailtempalte = 'email_tempalte'; //set our email template
    $transport = $this->_transportBuilder->setTemplateIdentifier($emailtempalte)
            ->setTemplateOptions($templateOptions)
            ->setTemplateVars($templateVars)
            ->addAttachment(file_get_contents($filePath),$fileName ,'application/pdf')
            ->setFrom($fromdata)
            ->addTo($to)
            ->getTransport();
    $transport->sendMessage();
    echo "message sent successfully with attachment";

}

}

create new TransportBuilder class and extend it with magento \Magento\Framework\Mail\Template\TransportBuilder class

namespace {{vendor}}\{{module}}\Model\Mail\Template;
class TransportBuilder extends \Magento\Framework\Mail\Template\TransportBuilder
{    
    protected $message;
    public function addAttachment($content, $fileName, $fileType)
    {
        $this->message->setBodyAttachment($content, $fileName, $fileType);
        return $this;
    }
    protected function prepareMessage()
    {
        parent::prepareMessage();
        $this->message->setPartsToBody();
        return $this;
    }
}

Execute upgrade and clean cache command and check it.

Ref Link

S.P
  • 1,534
  • 11
  • 16