0

How do we send email with attachments in magento 2 ? And file type be like .csv

Previously it was working when we were in 2.2x but after been upgrading to 2.3 it causing issues in attachments. And we did tried this extension as well but they are writing in a text file.

Expected Result : Load the file from the local path from module directory and attach it with email in M2.3

1

Try to use this below code in your helper:

<?php

namespace RH\MailSystem\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{

    /**
    * @var \Magento\Framework\App\Config\ScopeConfigInterface
    */
    protected $scopeConfig;

    /**
     * @var \Magento\Framework\Mail\Template\Factory
     */
    protected $templateFactory;

    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $_storeManager;

    /**
     * @var \Magento\Framework\Filesystem\Driver\File
     */
    protected $reader;

    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
        \Magento\Framework\Mail\Template\Factory $templateFactory,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\Filesystem\Driver\File $reader,
    ){
        $this->scopeConfig = $scopeConfig;
        $this->templateFactory = $templateFactory;
        $this->_storeManager = $storeManager;
        $this->reader = $reader;
    }


    public function sendMailtoSupport($subject, $message, $allfileatt)
    {
        try {
            $email_template = "your_email_templpate_id";
            $mail_to = $this->scopeConfig->getValue('trans_email/ident_general/email', \Magento\Store\Model\ScopeInterface::SCOPE_STORE); // sender email id
            $emailTemplateVariables['message'] = $message;
            $emailTemplateVariables['tempsubject'] = $subject;
            $postObject = new \Magento\Framework\DataObject();
            $postObject->setData($emailTemplateVariables);
            $zendTransport = $this->getEmailConfiguration();
            //Create email
            $senderName = $this->scopeConfig->getValue('trans_email/ident_general/name', \Magento\Store\Model\ScopeInterface::SCOPE_STORE); // sender name
            $senderEmail = $mail_to;
            $sendToEmail = $mail_to;
            $mail = new \Zend_Mail();
            $mail->setFrom($senderEmail, $senderName);
            $mail->addTo($sendToEmail);

            /**
             * Mail Attachement Code
             */
            foreach ($allfileatt as $value) {
                if ($value['fileName'] != "") {
                    $mediaUrl = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
                    $filePath = $mediaUrl . "ticketsystem/attachment/" . $value['new_fileName'];
                    $fileContent = $this->reader->fileGetContents($filePath);
                    $mail->createAttachment(
                        $fileContent,
                        \Zend_Mime::TYPE_OCTETSTREAM,
                        \Zend_Mime::DISPOSITION_ATTACHMENT,
                        \Zend_Mime::ENCODING_BASE64,
                        $value['fileName']
                    );
                }
            }
            $mail->setSubject($subject);
            $templateOptions = [
                'area' => \Magento\Framework\App\Area::AREA_FRONTEND,
                'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID,
            ];
            $htmlBody = $this->templateFactory->get($email_template, $this->templateModel)
                ->setVars(['data' => $postObject])
                ->setOptions($templateOptions)
                ->processTemplate();
            $mail->setBodyHtml($htmlBody);
            $mail->send($zendTransport);
            /*send attachment*/

        } catch (\Magento\Framework\Exception\LocalizedException $e) {
            return false;
        }

    }

    public function getEmailConfiguration()
    {
        $username = $this->getEmailConfig('username');
        $password = $this->getEmailConfig('password');
        $auth = strtolower($this->getEmailConfig('auth'));
        $smtpHost = $this->getEmailConfig('smtphost');
        $smtpConf = [
            'name' => $this->getEmailConfig('name'),
            'port' => $this->getEmailConfig('smtpport'),
        ];
        if ($auth != 'none') {
            $smtpConf['auth'] = $auth;
            $smtpConf['username'] = $username;
            $smtpConf['password'] = $password;
        }
        $ssl = $this->getEmailConfig('ssl');
        if ($ssl != 'none') {
            $smtpConf['ssl'] = $ssl;
        }
        $transport = new \Zend_Mail_Transport_Smtp($smtpHost, $smtpConf);
        return $transport;
    }

    private function getEmailConfig($key)
    {
        return $this->scopeConfig->getValue('system/gmailsmtpapp/' . $key,\Magento\Store\Model\ScopeInterface::SCOPE_STORE);
        // Return your SMTP configs value
    }
}

Now, call sendMailtoSupport() function with parameters from where you want to send.

enter image description here

I hope it will helpful for you.

  • In this, you need to pass array of current file name and new file name. – Rohan Hapani Jul 11 at 6:53
  • Like : [ 'new_fileName' => $new_fileName, 'fileName' => $fileName, ]; – Rohan Hapani Jul 11 at 6:53
  • Yes. You need to modify as per your SMTP extension. Which extension you used? I will attach screenshot. – Rohan Hapani Jul 11 at 7:00
  • I added screenshot. You can check it and get reference from it. – Rohan Hapani Jul 11 at 7:04
  • Let us continue this discussion in chat. – Rohan Hapani Jul 11 at 7:10

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.