cancel
Showing results for 
Search instead for 
Did you mean: 

Send mail from custom module magento 2

Send mail from custom module magento 2

Hello,

I work on my localhost.
I created a module that contains the sending of a personalized mail.
I arrived at the execute function of my controller sendemail.php but I have this error:

There has been an error processing your request

Also can I successfully send mail from my localhost?

Thanks in advance!

8 REPLIES

Re: Send mail from custom module magento 2

Could you please show your full code which you have tried for now?

Also check in your var/log or var/report folder to check error.

 

You can also send mail from local server. you need to get extension from link https://github.com/magepal/magento2-gmailsmtpapp

Install inside your project and follow steps which are defined in readme.php file in above module.

If Issue Solved, Click Kudos/Accept As solutions.

Re: Send mail from custom module magento 2

Thanks for your response!

this is my controller

<?php
namespace Excellence\Custom\Controller\Custom;

use Magento\Framework\App\RequestInterface;

class Sendemail 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(){

        $post = $this->getRequest()->getPostValue();
        $this->inlineTranslation->suspend();

        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

        $customerSession = $objectManager->create('Magento\Customer\Model\Session');

        try {
            $postObject = new \Magento\Framework\DataObject();

            $post['myname'] = $customerSession->getCustomer()->getName(); //Loggedin customer Name

            $post['myemail'] = $customerSession->getCustomer()->getEmail();

//Loggedin customer Email
            $postObject->setData($post);

            $myname = $post['myname'];

            $myemail = $post['myemail'];

            $sender = [
                'name' => $this->_escaper->escapeHtml($myname),
                'email' => $this->_escaper->escapeHtml($myemail),
            ];

            $sentToEmail = $this->scopeConfig->getValue('trans_email/ident_support/email',ScopeInterface::SCOPE_STORE);

            $sentToname = $this->scopeConfig->getValue('trans_email/ident_support/name',ScopeInterface::SCOPE_STORE);
            $senderBcc = 'my-test-account@gmail.com';
            $senderToInfo = [
                'name' => $this->_escaper->escapeHtml($sentToname),
                'email' => $this->_escaper->escapeHtml($sentToEmail),
            ];

            $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
            $transport = $this->_transportBuilder
                ->setTemplateIdentifier('mymodule_email_template') // My email template
                ->setTemplateOptions( [
                    'area' => \Magento\Framework\App\Area::AREA_FRONTEND, // this is using frontend area to get the template file if admin then \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE
                    'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID,
                ])
                ->setTemplateVars(['data' => $postObject])
                ->setFrom($sender)
                ->addTo($senderToInfo)
                ->addBcc($senderBcc)
                ->getTransport();

            $transport->sendMessage();

            $this->inlineTranslation->resume();

            $this->messageManager->addSuccess(__('Thanks'));

            $resultRedirect = $this->resultRedirectFactory->create();

            $resultRedirect->setRefererOrBaseUrl();
            $resultRedirect = $this->resultRedirectFactory->create();

            $resultRedirect->setRefererOrBaseUrl();

            return $resultRedirect;

        } catch (\Exception $e) {

            $this->inlineTranslation->resume();

            $this->messageManager->addError(__('Try again'));

            $resultRedirect = $this->resultRedirectFactory->create();

            $resultRedirect->setRefererOrBaseUrl();

            return $resultRedirect;
        }
    }
}

my email_templates.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:Magento:module:Magento_Email:etc/email_templates.xsd">
    <template id="myemail_email_template"
              label="Test email"
              file="myemail.html"
              type="html"
              module="Excellence_Custom"
              area="frontend"/>
</config>

In my var/log/debug.log

[2017-12-27 07:58:53] main.DEBUG: cache_invalidate:  {"method":"POST","url":"http://localhost/myshop/admin_1opt4l/admin/index/index/key/695153c2df3affcfdfb5f3af5155de0543f0ae8ed3ff2579d58f854432b1f831/","invalidateInfo":{"tags":["BACKEND_MAINMENU"],"mode":"matchingAnyTag"},"is_exception":false} []

Thanks in advance

Re: Send mail from custom module magento 2

Have you upload extension for Gmail Smtp? In your controller i dont find any issue and log is not related to any issue its general purpose message for cache validate.

If Issue Solved, Click Kudos/Accept As solutions.

Re: Send mail from custom module magento 2

I have a problem here

I want to install this module but it has been already defined in '/var/www/html/myshop/vendor/magepal/magento2-gmailsmtpapp'.

But in my configuration -> system->advanced I can't find it..

I tried to delete it and save in app/code

I had this error

require(/var/www/html/myshop/vendor/magepal/magento2-gmailsmtpapp/registration.php): failed to open stream: No such file or directory in /var/www/html/myshop/vendor/composer/autoload_real.php on line 60
PHP Fatal error:  require(): Failed opening required '/var/www/html/myshop/vendor/magepal/magento2-gmailsmtpapp/registration.php' (include_path='/var/www/html/myshop/vendor/magento/zendframework1/library:/var/www/html/myshop/vendor/phpunit/php-file-iterator:/var/www/html/myshop/vendor/phpunit/phpunit:/var/www/html/myshop/vendor/symfony/yaml:.:/usr/share/php') in /var/www/html/myshop/vendor/composer/autoload_real.php on line 60

 

Re: Send mail from custom module magento 2

You need to create folder like Magepal/GmailSmtpApp in your app/code folder and add all content of extension inside it.

Run upgrade and deploy command and after then you can check it.

If Issue Solved, Click Kudos/Accept As solutions.

Re: Send mail from custom module magento 2

To remove a module that is installed in /vendor you have to user composer (ie composer require magepal/magento2-gmailsmtpapp)

Re: Send mail from custom module magento 2

Seems like the module files were not uploaded to the correct location.

If you want to have a better understanding of how Magento sends emails, you can check this article.

Re: Send mail from custom module magento 2

Hello,

 

you need to first remove module from app/code

 

then run below command from your root directory

 

composer require magepal/magento2-gmailsmtpapp

 

then do setup upgrade and static content deploy.



If it will work then mark as solution.