cancel
Showing results for 
Search instead for 
Did you mean: 

Email With Multiple Images Not Sending ? Magento 2.3

Email With Multiple Images Not Sending ? Magento 2.3

I made a Module which has a form for customer to send his/her info with multiple images, Images saved to media folder on Submit also I get success message, but the Store Owner don't receive mail please review my code if you get any issue.

 

app/code/[Vendor]/[Module]/Controller/Index/Post.php

<?php
/**
 *
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace [Vendor]\[Module]\Controller\Index;

use Magento\Contact\Model\ConfigInterface;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\App\Filesystem\DirectoryList;

class Post extends \Magento\Contact\Controller\Index
{
    /**
     * @var DataPersistorInterface
     */
    private $dataPersistor;   

    /**
     * Post user question
     *
     * @return void
     * @throws \Exception
     */
    private $scopeConfig;

    /**
     * @var \Magento\Directory\Model\CountryFactory
     */
    private $countryFactory;

    private $inlineTranslation;
    /**
     * @var \Magento\Framework\Mail\Template\TransportBuilder
     */
    protected $_transportBuilder;

    /**
     * @var \Magento\Directory\Model\Region
     */
    private $region;

    /**
     * @var \Magento\Framework\Filesystem
     */
    protected $_filesystem;

    /**
     * Post constructor.
     * @param Context $context
     * @param ConfigInterface $contactsConfig
     * @param \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder
     * @param ScopeConfigInterface $scopeConfig
     * @param \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation
     * @param \Magento\Directory\Model\CountryFactory $countryFactory
     * @param \Magento\Directory\Model\Region $region
     */
    public function __construct(
        Context $context,
        ConfigInterface $contactsConfig,
        \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder,
        ScopeConfigInterface $scopeConfig,
        \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation,
        \Magento\Directory\Model\CountryFactory $countryFactory,
        \Magento\Directory\Model\Region $region,
        \Magento\Framework\Filesystem $filesystem
    ) {
        parent::__construct($context, $contactsConfig);
        $this->_transportBuilder = $transportBuilder;
        $this->scopeConfig = $scopeConfig;
        $this->inlineTranslation = $inlineTranslation;
        $this->countryFactory = $countryFactory;
        $this->region = $region;
        $this->_filesystem = $filesystem;
    }

    /**
     * @return bool|\Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface
     */
    public function execute() {
      $post = $this->getRequest()->getPostValue();
      $postObject = new \Magento\Framework\DataObject();
      $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
      $storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
      $webURl = $storeManager->getStore()->getBaseUrl();

      $name = trim($post['name']);
      $email = trim($post['email']);

      $address = (isset($post['address']) && !empty($post['address'])) ? trim($post['address']) : 'N/A';
      $city = (isset($post['city']) && !empty($post['city'])) ? trim($post['city']) : 'N/A';
      $state = (isset($post['region']) && !empty($post['region'])) ? $this->getRegionName(trim($post['region'])) : "N/A";
      $country = (isset($post['country_id']) && !empty($post['country_id'])) ? $this->getCountryName($post['country_id']) : 'N/A';
      $zip = (isset($post['zip']) && !empty($post['zip']) ) ? trim($post['zip']) : 'N/A';
      $tel = (isset($post['tel']) && !empty($post['tel'])) ? trim($post['tel']) : 'N/A';
      $employer = (isset($post['employer']) && !empty($post['employer'])) ? trim($post['employer']) : 'N/A';
      $jobtitle = (isset($post['jobtitle']) && !empty($post['jobtitle'])) ? trim($post['jobtitle']) : 'N/A';

      $post['address'] = $address;
      $post['city'] = $city;
      $post['state'] = $state;
      $post['zip'] = $zip;
      $post['tel'] = $tel;
      $post['employer'] = $employer;
      $post['jobtitle'] = $jobtitle;

      $postObject->setData($post);

      //print_r($post); die;

      $fileName = '';
      $attachment = '';

      // Count # of uploaded files in array
      $total = count($_FILES['attachment']['name']);

      // Loop through each file
      for( $i=0 ; $i < $total ; $i++ ) {
        if (isset($_FILES['attachment']['name'][$i]) && $_FILES['attachment']['name'][$i] != '') {
            try {
                $fileName = $_FILES['attachment']['name'][$i];
                $fileExt = strtolower(substr(strrchr($fileName, ".") ,1));
                $fileNamewoe = explode('.', $fileName);
                $fileName = str_replace(' ', '', $fileNamewoe[0]) . time() . '.' . $fileExt;

                $mediapath = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath();
                if(move_uploaded_file($_FILES['attachment']['tmp_name'][$i], $mediapath . 'procard/'.$fileName)){
                    $attachment = $mediapath . 'procard/'.$fileName;
                }

            } catch (Exception $e) {
                $this->messageManager->addError($e->getMessage());
                $error = true;
            }
        }
      }

      $templateId = 2;

      $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;

      if($attachment != ''){

          $transports = $this->_transportBuilder->setTemplateIdentifier($templateId)
          ->setTemplateOptions(
              [
                  'area' => \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE,
                  'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID,
              ]
          )
          ->setTemplateVars(['data' => $postObject])
          ->setFrom($this->scopeConfig->getValue(self::XML_PATH_EMAIL_SENDER, $storeScope))
          ->addTo($this->scopeConfig->getValue(self::XML_PATH_EMAIL_RECIPIENT, $storeScope))
          ->addAttachment(file_get_contents($attachment),$fileName)
          ->getTransport();
      }
      else{

          $transports = $this->_transportBuilder->setTemplateIdentifier($templateId)
          ->setTemplateOptions(
              [
                  'area' => \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE,
                  'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID,
              ]
          )
          ->setTemplateVars(['data' => $postObject])
          ->setFrom($this->scopeConfig->getValue(self::XML_PATH_EMAIL_SENDER, $storeScope))
          ->addTo($this->scopeConfig->getValue(self::XML_PATH_EMAIL_RECIPIENT, $storeScope))
          ->getTransport();
      }

      try {
          $transports->sendMessage();
      } catch (LocalizedException $exception) {
          $this->messageManager->addError($exception->getMessage());
          $this->_redirect($this->_redirect->getRefererUrl());
          return false;
      }
      $this->inlineTranslation->resume();

      $this->messageManager->addSuccess(
        __('Success!<br>Your Pro Card application has been received. <br> We will get back to you soon.')
      );

      $this->getDataPersistor()->clear('pro-card');
      $this->_redirect($this->_redirect->getRefererUrl());
    }    

    /**
     * Get Data Persistor
     *
     * @return DataPersistorInterface
     */
    private function getDataPersistor()
    {
        if ($this->dataPersistor === null) {
            $this->dataPersistor = ObjectManager::getInstance()
                ->get(DataPersistorInterface::class);
        }

        return $this->dataPersistor;
    }

    /**
     * @param $countryCode
     * @return string
     */
    public function getCountryName($countryCode){
        $country = $this->countryFactory->create()->loadByCode($countryCode);
        return $country->getName();
    }

    /**
     * @param $regionId
     * @return bool|string
     */
    public function getRegionName($regionId)
    {
        try {
            $region = $this->region->load($regionId);
            return $region->getName();
        } catch (NoSuchEntityException $exception) {
            return false;
        }
    }
}

app/code/[Vendor]/[Module]/Mail/Template/TransportBuilder.php

<?php
namespace [Vendor]\[Module]\Mail\Template;

class TransportBuilder extends \Magento\Framework\Mail\Template\TransportBuilder
{
    public function addAttachment(
                            $body,
                            $mimeType = \Zend_Mime::TYPE_OCTETSTREAM,
                            $disposition = \Zend_Mime::DISPOSITION_ATTACHMENT,
                            $encoding = \Zend_Mime::ENCODING_BASE64,
                            $filename = null)
    {
        //$this->message->createAttachment($body, $mimeType, $disposition, $encoding, $filename);
        $this->message->createCustomAttachment($body, $mimeType, $disposition, $encoding, $filename);
        return $this;
    }
}

app/code/[Vendor]/[Module]/Mail/Message.php

<?php

namespace [Vendor]\[Module]\Mail;

use Zend\Mime\Mime;
use Zend\Mime\Part;

/**
 * Class Message for email transportation
 */
class Message implements \Magento\Framework\Mail\MailMessageInterface
{
    /**
     * @var \Zend\Mail\Message
     */
    private $zendMessage;
    private $attachment;

    /**
     * Message type
     *
     * @var string
     */
    private $messageType = self::TYPE_TEXT;

    /**
     * Initialize dependencies.
     *
     * @param string $charset
     */
    public function __construct($charset = 'utf-8')
    {
        $this->zendMessage = new \Zend\Mail\Message();
        $this->zendMessage->setEncoding($charset);
    }

    /**
     * @inheritdoc
     *
     * @deprecated 101.0.8
     * @see \Magento\Framework\Mail\Message::setBodyText
     * @see \Magento\Framework\Mail\Message::setBodyHtml
     */
    public function setMessageType($type)
    {
        $this->messageType = $type;
        return $this;
    }

    /**
     * @inheritdoc
     *
     * @deprecated 101.0.8
     * @see \Magento\Framework\Mail\Message::setBodyText
     * @see \Magento\Framework\Mail\Message::setBodyHtml
     */
    public function setBody($body)
    {
        if (is_string($body) && $this->messageType === \Magento\Framework\Mail\MailMessageInterface::TYPE_HTML) {
            $body = self::createHtmlMimeFromString($body);
        }
        $this->zendMessage->setBody($body);
        return $this;
    }

    /**
     * @inheritdoc
     */
    public function setSubject($subject)
    {
        $this->zendMessage->setSubject($subject);
        return $this;
    }

    /**
     * @inheritdoc
     */
    public function getSubject()
    {
        return $this->zendMessage->getSubject();
    }

    /**
     * @inheritdoc
     */
    public function getBody()
    {
        return $this->zendMessage->getBody();
    }

    /**
     * @inheritdoc
     *
     * @deprecated 102.0.1 This function is missing the from name. The
     * setFromAddress() function sets both from address and from name.
     * @see setFromAddress()
     */
    public function setFrom($fromAddress)
    {
        $this->setFromAddress($fromAddress, null);
        return $this;
    }

    /**
     * @inheritdoc
     */
    public function setFromAddress($fromAddress, $fromName = null)
    {
        $this->zendMessage->setFrom($fromAddress, $fromName);
        return $this;
    }

    /**
     * @inheritdoc
     */
    public function addTo($toAddress)
    {
        $this->zendMessage->addTo($toAddress);
        return $this;
    }

    /**
     * @inheritdoc
     */
    public function addCc($ccAddress)
    {
        $this->zendMessage->addCc($ccAddress);
        return $this;
    }

    /**
     * @inheritdoc
     */
    public function addBcc($bccAddress)
    {
        $this->zendMessage->addBcc($bccAddress);
        return $this;
    }

    /**
     * @inheritdoc
     */
    public function setReplyTo($replyToAddress)
    {
        $this->zendMessage->setReplyTo($replyToAddress);
        return $this;
    }

    /**
     * @inheritdoc
     */
    public function getRawMessage()
    {
        return $this->zendMessage->toString();
    }

    /**
     * Create HTML mime message from the string.
     *
     * @param string $htmlBody
     * @return \Zend\Mime\Message
     */
    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;
    }

    /**
     * @inheritdoc
     */
    public function setBodyHtml($html)
    {
        $this->setMessageType(self::TYPE_HTML);
        return $this->setBody($html);
    }

    /**
     * @inheritdoc
     */
    public function setBodyText($text)
    {
        $this->setMessageType(self::TYPE_TEXT);
        return $this->setBody($text);
    }

    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;
    }
}
2 REPLIES 2

Re: Email With Multiple Images Not Sending ? Magento 2.3

@Partab Saif 

first try to send a simple mail.

i think your mail is not sending on your server.

Please check once.

 

Thanks

Re: Email With Multiple Images Not Sending ? Magento 2.3

@Rahul Gupta all mail are working as expected, I mean for newsletter, password etc, please refer magento-2-3-custom-email-attachment-not-working