Emails are one of the traditional & cheapest ways to send updates to the customers. Today, almost every CMS provides the functionality to engage and stay connected with users via emails. And Magento does the same and provides an email automation system that notifies store customers every time their order status gets updated or changed. Taking it to the next level, Magento also generates and sends order doc PDFs as an email attachment to the customers. So they can have virtual docs of their purchase.
But with the update to Magento 2.3.3, many Magento 2 store owners are facing an issue while sending PDF as an email attachment. It seems like there an issue in their core and one needs to fix it so all the store owners can fix and continue to use their upgraded Magento 2.3.3. So, if you are in search of fixing a PDF attachment issue, your search ends here. Just follow these steps and your email attachment will start working like charm as it worked previously.
First, you need to create “di.xml” file inside your extension folder.
app/code/VENDOR/EXTENSION/etc/
1 2 3 |
<pre class="lang:default decode:true"> <preference for="\Magento\Framework\Mail\Template\TransportBuilder" type="VENDOR\EXTENSION\Model\Mail\Template\TransportBuilder" /> </pre> |
Now, you have to create one more file “transportBuilder.php” inside your template folder with below code.
app/code/VENDOR/EXTENSION/model/mail/template/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 |
<pre class="lang:default decode:true"> <?php declare(strict_types=1); namespace VENDOR\EXTENSION\Model\Mail\Template; use Magento\Framework\App\TemplateTypesInterface; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\MailException; use Magento\Framework\Mail\EmailMessageInterface; use Magento\Framework\Mail\EmailMessageInterfaceFactory; use Magento\Framework\Mail\AddressConverter; use Magento\Framework\Mail\Exception\InvalidArgumentException; use Magento\Framework\Mail\MessageInterface; use Magento\Framework\Mail\MessageInterfaceFactory; use Magento\Framework\Mail\MimeInterface; use Magento\Framework\Mail\MimeMessageInterfaceFactory; use Magento\Framework\Mail\MimePartInterfaceFactory; use Magento\Framework\Mail\Template\FactoryInterface; use Magento\Framework\Mail\Template\SenderResolverInterface; use Magento\Framework\Mail\TemplateInterface; use Magento\Framework\Mail\TransportInterface; use Magento\Framework\Mail\TransportInterfaceFactory; use Magento\Framework\ObjectManagerInterface; use Magento\Framework\Phrase; use Zend\Mime\Mime; use Zend\Mime\PartFactory; /** * TransportBuilder * * @api * @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @since 100.0.2 */ class TransportBuilder extends \Magento\Framework\Mail\Template\TransportBuilder { /** * Template Identifier * * @var string */ protected $templateIdentifier; /** * Template Model * * @var string */ protected $templateModel; /** * Template Variables * * @var array */ protected $templateVars; /** * Template Options * * @var array */ protected $templateOptions; /** * Mail Transport * * @var TransportInterface */ protected $transport; /** * Template Factory * * @var FactoryInterface */ protected $templateFactory; /** * Object Manager * * @var ObjectManagerInterface */ protected $objectManager; /** * Message * * @var EmailMessageInterface */ protected $message; /** * Sender resolver * * @var SenderResolverInterface */ protected $_senderResolver; /** * @var TransportInterfaceFactory */ protected $mailTransportFactory; /** * Param that used for storing all message data until it will be used * * @var array */ private $messageData = []; /** * @var EmailMessageInterfaceFactory */ private $emailMessageInterfaceFactory; /** * @var MimeMessageInterfaceFactory */ private $mimeMessageInterfaceFactory; /** * @var MimePartInterfaceFactory */ private $mimePartInterfaceFactory; /** * @var AddressConverter|null */ private $addressConverter; protected $attachments = []; protected $partFactory; /** * TransportBuilder constructor * * @param FactoryInterface $templateFactory * @param MessageInterface $message * @param SenderResolverInterface $senderResolver * @param ObjectManagerInterface $objectManager * @param TransportInterfaceFactory $mailTransportFactory * @param MessageInterfaceFactory|null $messageFactory * @param EmailMessageInterfaceFactory|null $emailMessageInterfaceFactory * @param MimeMessageInterfaceFactory|null $mimeMessageInterfaceFactory * @param MimePartInterfaceFactory|null $mimePartInterfaceFactory * @param addressConverter|null $addressConverter * @SuppressWarnings(PHPMD.UnusedFormalParameter) * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( FactoryInterface $templateFactory, MessageInterface $message, SenderResolverInterface $senderResolver, ObjectManagerInterface $objectManager, TransportInterfaceFactory $mailTransportFactory, MessageInterfaceFactory $messageFactory = null, EmailMessageInterfaceFactory $emailMessageInterfaceFactory = null, MimeMessageInterfaceFactory $mimeMessageInterfaceFactory = null, MimePartInterfaceFactory $mimePartInterfaceFactory = null, AddressConverter $addressConverter = null ) { $this->templateFactory = $templateFactory; $this->objectManager = $objectManager; $this->_senderResolver = $senderResolver; $this->mailTransportFactory = $mailTransportFactory; $this->emailMessageInterfaceFactory = $emailMessageInterfaceFactory ?: $this->objectManager ->get(EmailMessageInterfaceFactory::class); $this->mimeMessageInterfaceFactory = $mimeMessageInterfaceFactory ?: $this->objectManager ->get(MimeMessageInterfaceFactory::class); $this->mimePartInterfaceFactory = $mimePartInterfaceFactory ?: $this->objectManager ->get(MimePartInterfaceFactory::class); $this->addressConverter = $addressConverter ?: $this->objectManager ->get(AddressConverter::class); $this->partFactory = $objectManager->get(PartFactory::class); parent::__construct($templateFactory, $message, $senderResolver, $objectManager, $mailTransportFactory, $messageFactory, $emailMessageInterfaceFactory, $mimeMessageInterfaceFactory, $mimePartInterfaceFactory, $addressConverter); } /** * Add cc address * * @param array|string $address * @param string $name * * @return $this */ public function addCc($address, $name = '') { $this->addAddressByType('cc', $address, $name); return $this; } /** * Add to address * * @param array|string $address * @param string $name * * @return $this * @throws InvalidArgumentException */ public function addTo($address, $name = '') { $this->addAddressByType('to', $address, $name); return $this; } /** * Add bcc address * * @param array|string $address * * @return $this * @throws InvalidArgumentException */ public function addBcc($address) { $this->addAddressByType('bcc', $address); return $this; } /** * Set Reply-To Header * * @param string $email * @param string|null $name * * @return $this * @throws InvalidArgumentException */ public function setReplyTo($email, $name = null) { $this->addAddressByType('replyTo', $email, $name); return $this; } /** * Set mail from address * * @param string|array $from * * @return $this * @throws InvalidArgumentException * @see setFromByScope() * * @deprecated 102.0.1 This function sets the from address but does not provide * a way of setting the correct from addresses based on the scope. */ public function setFrom($from) { return $this->setFromByScope($from); } /** * Set mail from address by scopeId * * @param string|array $from * @param string|int $scopeId * * @return $this * @throws InvalidArgumentException * @throws MailException * @since 102.0.1 */ public function setFromByScope($from, $scopeId = null) { $result = $this->_senderResolver->resolve($from, $scopeId); $this->addAddressByType('from', $result['email'], $result['name']); return $this; } /** * Set template identifier * * @param string $templateIdentifier * * @return $this */ public function setTemplateIdentifier($templateIdentifier) { $this->templateIdentifier = $templateIdentifier; return $this; } /** * Set template model * * @param string $templateModel * * @return $this */ public function setTemplateModel($templateModel) { $this->templateModel = $templateModel; return $this; } /** * Set template vars * * @param array $templateVars * * @return $this */ public function setTemplateVars($templateVars) { $this->templateVars = $templateVars; return $this; } /** * Set template options * * @param array $templateOptions * @return $this */ public function setTemplateOptions($templateOptions) { $this->templateOptions = $templateOptions; return $this; } /** * Get mail transport * * @return TransportInterface * @throws LocalizedException */ public function getTransport() { try { $this->prepareMessage(); $mailTransport = $this->mailTransportFactory->create(['message' => clone $this->message]); } finally { $this->reset(); } return $mailTransport; } /** * Reset object state * * @return $this */ protected function reset() { $this->messageData = []; $this->templateIdentifier = null; $this->templateVars = null; $this->templateOptions = null; return $this; } /** * Get template * * @return TemplateInterface */ protected function getTemplate() { return $this->templateFactory->get($this->templateIdentifier, $this->templateModel) ->setVars($this->templateVars) ->setOptions($this->templateOptions); } /** * Prepare message. * * @return $this * @throws LocalizedException if template type is unknown */ protected function prepareMessage() { $template = $this->getTemplate(); $content = $template->processTemplate(); switch ($template->getType()) { case TemplateTypesInterface::TYPE_TEXT: $part['type'] = MimeInterface::TYPE_TEXT; break; case TemplateTypesInterface::TYPE_HTML: $part['type'] = MimeInterface::TYPE_HTML; break; default: throw new LocalizedException( new Phrase('Unknown template type') ); } $mimePart = $this->mimePartInterfaceFactory->create(['content' => $content]); $parts = count($this->attachments) ? array_merge([$mimePart], $this->attachments) : [$mimePart]; $this->messageData['body'] = $this->mimeMessageInterfaceFactory->create( ['parts' => $parts] ); $this->messageData['subject'] = html_entity_decode( (string)$template->getSubject(), ENT_QUOTES ); $this->message = $this->emailMessageInterfaceFactory->create($this->messageData); return $this; } /** * Handles possible incoming types of email (string or array) * * @param string $addressType * @param string|array $email * @param string|null $name * * @return void * @throws InvalidArgumentException */ private function addAddressByType(string $addressType, $email, ?string $name = null): void { if (is_string($email)) { $this->messageData[$addressType][] = $this->addressConverter->convert($email, $name); return; } $convertedAddressArray = $this->addressConverter->convertMany($email); if (isset($this->messageData[$addressType])) { $this->messageData[$addressType] = array_merge( $this->messageData[$addressType], $convertedAddressArray ); } } /** * @param string|null $content * @param string|null $fileName * @param string|null $fileType * @return TransportBuilder */ public function addAttachment(?string $content, ?string $fileName, ?string $fileType) { $attachmentPart = $this->partFactory->create(); $attachmentPart->setContent($content) ->setType($fileType) ->setFileName($fileName) ->setDisposition(Mime::DISPOSITION_ATTACHMENT) ->setEncoding(Mime::ENCODING_BASE64); $this->attachments[] = $attachmentPart; return $this; } } </pre> |
Lastly, we have create a call to the file as shown below.
1 2 3 |
<pre class="lang:default decode:true"> $this->transportBuilder->addAttachment($content, $fileName, 'application/pdf'); </pre> |
That’t it. Now your email attachment issue is resolved. You are free to manipulate this code according to your need.
Lastly, if you found this blog helpful, don’t forget to share it with your colleagues and Magento Friends and Let us know if you are facing any issue while implementing this code.
Happy Coding!
Facing this,run all commands but not solving:: Type Error occurred when creating object: Magento\Framework\Mail\EmailMessage\Interceptor, Argument 2 passed to Magento\Framework\Mail\EmailMessage\Interceptor::__construct() must be of the type array, null given, called in /var/www/html/magento/vendor/magento/framework/ObjectManager/Factory/AbstractFactory.php on line 121
Hi Dhiren
I am implementing this code in my project (m233) but i am getting error like below..
{“0″:”Missing required argument $to of Magento\\Framework\\Mail\\EmailMessage.”,”1″:”#1 Magento\\Framework\\ObjectManager\\Factory\\AbstractFactory->resolveArgumentsInRuntime(‘Magento\\Framewor…’, array(array(‘body’, ‘Magento\\Framewor…’, true, NULL, false), array(‘to’, NULL, true, NULL, false), array(‘mimeMessageFacto…’, ‘Magento\\Framewor…’, true, NULL, false),
can you please share me the full code where you have used this and mail attachment is performed.
If I use same code for .DOC file it’s giving error: Disallowed file type. I am dynamically passing file type as function parameter. Do you have any idea?