0

I have a problem, i composered smtp in github and i want create send mail

I have file app/code/Mageplaza/HelloWorld/etc/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="helloworld_options_helloworld_group_email_template_invalid" 
            label="Email template invalid" 
            file="email/helloworld_email_template_invalid.html" 
            type="html" 
            module="Mageplaza_HelloWorld" 
            area="frontend"
/>
</config>

I have file app/code/Mageplaza/HelloWorld/view/frontend/email/helloworld_emai_template_invalid.html

<!--@subject Email Subject @-->
<!--@vars
{"store url = \"\"":"Store Url",
"skin url=\"images/logo_email.gif\" _area='frontend'":"Email Logo Image",
"htmlescape var=$recipient_name":"Recipient Name",
"htmlescape var=$recipient_email":"Recipient Email"}
@-->

<!--@styles
body {background: #F6F6F6; margin: 0; padding: 0;}
body, td {
color:#2f2f2f; font:11px/1.35em Verdana, Arial, Helvetica, sans-serif;
}
@-->

<body>
<div>
    <table cellspcing="0" cellpadding="0" border="0" height="100%" width="100%">
        <tr>
            <td align="center" valign="top" style="padding:20px 0 20px 0">
                <!-- [header starts here] -->
                <table bgcolor="FFFFFF" cellspacing="0" cellpadding="10" border="0" width="650" style="border:1px solid #E0E0E0">
                    <!-- [middle starts here] -->
                    <tr>
                        <td valign="top">
                            <h1 style="font-size:22px; font-weight: normal; line-height: 22px; margin:0 0 11px 0">Dear {{var email}},</h1>
                            This is the email that send from our magento system
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <p>Congratulation you signup complete</p>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <p>You has buy a ticket {{var name}} with type is {{var typeId}}</p>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <p>A ticket {{var typeId}} has changes about status: {{var statusId}} </p>        
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <a href="{{store url="ticket/frontend/manageaticket/"}}uniqueCode/{{var uniqueCode}}"><span>View Detail Ticket</span></a>
                            <br/>
                            view: {{store url="ticket/frontend/manageaticket/"}}uniqueCode/{{var uniqueCode}}
                        </td>
                    </tr>
                    <tr>
                        <td bgcolor="#EAEAEA" align="center" style="background:#EAEAEA; text-align: center;">
                            <center>
                                <p style="font-size:12px; margin:0">
                                    Thank you again, <strong>{{var store.getFrontendName()}}</strong>
                                </p>
                            </center>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</div>
</body>

I have file app/code/Mageplaza/HelloWorld/Helper/Email.php

<?php

namespace Mageplaza\HelloWorld\Helper;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Customer\Model\Session as CustomerSession;
use Magento\Framework\Exception\MailException;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\Translate\Inline\StateInterface;
use Magento\Framework\Mail\Template\TransportBuilder;
use Magento\Framework\Message\ManagerInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\UrlInterface;

class Email extends AbstractHelper {
const EMAIL_APPROVAL_INVALID = 'helloworld_options/helloworld_group/email_template_invalid';
/**
 * @var StateInterface
 */
protected $_inlineTranslation;

/**
 * @var TransportBuilder
 */
protected $_transportBuilder;

/**
 * @var CustomerSession
 */
protected $_customerSession;

/**
 * @var StoreManagerInterface
 */
protected $_storeManager;

/**
 * @var UrlInterface
 */
protected $_url;

protected $_template;

protected $_messageManager;

public function __construct(
    Context $context,
    StateInterface $inlineTranslation,
    TransportBuilder $transportBuilder,
    ManagerInterface $messageManager,
    StoreManagerInterface $storeManager,
    CustomerSession $customerSession,
    UrlInterface $url
) {
    parent::__construct($context);
    $this->_inlineTranslation = $inlineTranslation;
    $this->_transportBuilder = $transportBuilder;
    $this->_customerSession = $customerSession;
    $this->_storeManager = $storeManager;
    $this->_messageManager = $messageManager;
    $this->_url = $url;
}

protected function getConfigValue($path, $storeId) {
    return $this->scopeConfig->getValue(
        $path,
        \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
        $storeId
    );
}

protected function getTemplateId($xmlPath) {
    return $this->getConfigValue($xmlPath, $this->_storeManager->getStore()->getId());
}

protected function generateTemplate($emailTemplateVariables, $senderInfo, $receiverInfo) {
    $template = $this->_transportBuilder->setTemplateIdentifier($this->_template)
        ->setTemplateOptions(
            [
                'area' => \Magento\Framework\App\Area::AREA_FRONTEND,
                'store' => $this->_storeManager->getStore()->getId(),
            ]
        )
        ->setTemplateVars($emailTemplateVariables)
        ->setFrom($senderInfo)
        ->addTo($receiverInfo['email'], $receiverInfo['name'])
        ->setReplyTo($senderInfo['email'], $senderInfo['name']);

    return $this;
}

public function sendEmail($template, $emailTemplateVariables){
    $result = [
        'error' => false
    ];
    $this->_template = $this->getTemplateId($template);

    $this->_inlineTranslation->suspend();

    $senderInfo = [
        'email' => $this->getConfigValue( 'trans_email/ident_custom2/email', $this->_storeManager->getStore()->getId()),
        'name' => $this->getConfigValue( 'trans_email/ident_general/name', $this->_storeManager->getStore()->getId())
    ];

    $receiverInfo = [
        'email' => $emailTemplateVariables['email'],
        'name' => $emailTemplateVariables['name']
    ];

    $this->generateTemplate($emailTemplateVariables, $senderInfo, $receiverInfo);

    try {
        $transport = $this->_transportBuilder->getTransport();
        $transport->sendMessage();
        $result = [
            'error' => false,
            'message' => 'Email is sent successfully'
        ];
    } catch (\Exception $e) {
        $result = [
            'error' => true,
            'message' => $e->getMessage()
        ];
    }

    $this->_inlineTranslation->resume();

    return $result;
}

public function sendEmailHelloWorldInvalid($emailTempVariables) {
    $this->sendEmail(self::EMAIL_APPROVAL_INVALID, $emailTempVariables);
}
}

And i have file app/code/Mageplaza/HelloWorld/Controller/Adminhtml/Post/SendMail.php

    <?php

    namespace Mageplaza\HelloWorld\Controller\Adminhtml\Post;

    use Magento\Framework\Event\ObserverInterface;
    use Mageplaza\HelloWorld\Helper\Email;

    class SendMail implements ObserverInterface
{
    private $helperEmail;

    public function __construct(
        Email $helperEmail
    ) {
        $this->helperEmail = $helperEmail;
    }
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $data['name'] = 'Boll';
        $data['email'] = 'abc@gmail.com';

        return $this->helperEmail->sendEmailHelloWorldInvalid($data);
    }
    }

I don't know which file I am missing. Help me please!

1

check your controller SendMail.php. you implement ObserverInterface in that controller correct is controller always extend Magento\Backend\App\Action.

<?php

namespace Mageplaza\HelloWorld\Controller\Adminhtml\Post;

use Magento\Backend\App\Action;
use Magento\Framework\Event\ObserverInterface;
use Mageplaza\HelloWorld\Helper\Email;

class SendMail extends Action
{
    private $helperEmail;

    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory,
        Email $helperEmail
    ) {
        parent::__construct($context);
        $this->resultPageFactory = $resultPageFactory;
        $this->helperEmail = $helperEmail;
    }

    public function execute()
    {
        $data['name'] = 'Boll';
        $data['email'] = 'khazjx123@gmail.com';
        $resultRedirect = $this->resultRedirectFactory->create();

        try {
            $this->helperEmail->sendEmailHelloWorldInvalid($data);
            $this->messageManager->addSuccessMessage(__('You send mail success.'));
            return $resultRedirect->setPath('mageplaza_helloworld/post/index');
        } catch (\Exception $e) {
            $this->messageManager->addErrorMessage($e->getMessage());
            $this->messageManager->addExceptionMessage($e, __('Something went wrong while saving the record.'));
        }
        return $resultRedirect->setPath('mageplaza_helloworld/post/index');
    }
}
| improve this answer | |
  • it working. thank you devidas – Boll Jun 2 at 8:13
  • great ...! Welcome @HưngNguyễn – Devidas Jun 2 at 8:25

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.