0

I was lots of tries to send the attachment to mail but no luck. Please check my below code and please correct me where I am wrong.

<?php
/**
 * KiwiCommerce
 *
 * Do not edit or add to this file if you wish to upgrade to newer versions in the future.
 * If you wish to customize this module for your needs.
 * Please contact us https://kiwicommerce.co.uk/contacts.
 *
 * @category   KiwiCommerce
 * @package    KiwiCommerce_AdminActivity
 * @copyright  Copyright (C) 2018 Kiwi Commerce Ltd (https://kiwicommerce.co.uk/)
 * @license    https://kiwicommerce.co.uk/magento2-extension-license/
 */
namespace KiwiCommerce\AdminActivity\Cron;

use Magento\Framework\App\RequestInterface;

/**
 * Class ClearLog
 * @package KiwiCommerce\AdminActivity\Cron
 */
class Test extends \Magento\Framework\App\Action\Action
{
  /**
     * @var \Magento\Framework\App\Request\Http
     */
    protected $_request;
    /**
     * @var \Magento\Framework\Mail\Template\TransportBuilder
     */
    protected $_transportBuilder;
    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $_storeManager;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\App\Request\Http $request,
        \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder,
        \Magento\Store\Model\StoreManagerInterface $storeManager
    )
    {
        $this->_request = $request;
        $this->_transportBuilder = $transportBuilder;
        $this->_storeManager = $storeManager;
        parent::__construct($context);
    }

    public function execute()
    {
        $filePath = 'C:/new/xampp/htdocs/Uplifting-Products/var/export/Adminactivity/admin_activity_09_11_2019_14_35_49.csv';

        $fileName = 'admin_activity_09_11_2019_14_35_49.csv';

        $store = $this->_storeManager->getStore()->getId();
        $transport = $this->_transportBuilder->setTemplateIdentifier('modulename_test_template')
            ->setTemplateOptions(['area' => 'frontend', 'store' => $store])
            ->setTemplateVars(
                [
                    'store' => $this->_storeManager->getStore(),
                ]
            )
            ->setFrom('general')
            // you can config general email address in Store -> Configuration -> General -> Store Email Addresses
            ->addTo('[email protected]', 'Customer Name')
            ->addAttachment($filePath,$fileName)
            ->getTransport();
        $transport->sendMessage();
        return $this;
    }
}

Also i have completed the below process after run above code.

To add an attachment programmatically in the email, first, you need to override \Magento\Framework\Mail\Template\TransportBuilder class.

Step 1: app/code/[Namespace]/[Module]/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="\Magento\Framework\Mail\Template\TransportBuilder" type="\[Namespace]\[Module]\Mail\Template\TransportBuilder" />
</config>
Step 2: app/code/[Namespace]/[Module]/Mail/Template/TransportBuilder.php

<?php

namespace [Namespace]\[Module]\Mail\Template;

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

    public function addAttachment(
    $filePath, $filename = null, $mimeType = \Zend_Mime::TYPE_OCTETSTREAM, $disposition = \Zend_Mime::DISPOSITION_ATTACHMENT, $encoding = \Zend_Mime::ENCODING_BASE64
    ) {
        if (file_exists($filePath)) {
            $body = file_get_contents($filePath);
            $this->message->createAttachment($body, $mimeType, $disposition, $encoding, $filename);
        }
        return $this;
    }

}

Now, you can call addAttachment() function while sending an email.

Note: addAttachment function requires 2 parameters: filePath and fileName.

4

1 Answer 1

0

for magento 2.2.8, 2.2.9, 2.3.0, 2.3.1, 2.3.2 versions you can check this solution

https://github.com/extait-com/email-attachment

for email attachment

5
  • but how can i use in my module.
    – AKM
    Sep 12, 2019 at 7:37
  • in above solution you can add code to your custom module just copy code. if file exist then simply add code if file not created then create file in path. Sep 12, 2019 at 9:09
  • It's give me error like below [2019-09-12 09:44:35] main.CRITICAL: Error when running a cron job {"exception":"[object] (RuntimeException(code: 0): Error when running a cron job at C:\ ew\\xampp\\htdocs\\Uplifting-Products\\vendor\\magento\\module-cron\\Observer\\ProcessCronQueueObserver.php:327, Error(code: 0): Call to undefined method KiwiCommerce\\EnhancedSMTP\\Email\\Log\\SaveEmailLog\\Interceptor::addAttachment() at C:\ ew\\xampp\\htdocs\\Uplifting-Products\\app\\code\\KiwiCommerce\\AdminActivity\\Cron\\Test.php:64)"} []
    – AKM
    Sep 12, 2019 at 10:00
  • can you refer this may be it's helps you github.com/mageplaza/magento-2-email-attachments/issues/4 Sep 12, 2019 at 10:34
  • @ chandresh chauhan i am not using mageplaza module.
    – AKM
    Sep 12, 2019 at 11:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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