1

I am new to this magento. I want to send a email and display a success message in magento2. Anyone please give me a solution for sending a mail programmatically.

  • You want so send mail from a custom form in front end or in backend? – Nero Phung Nov 25 '17 at 8:42
3

Create your controller

<?php

namespace Vendor\Module\Controller\Index;

use Magento\Framework\Mail\Template\TransportBuilder;
use Magento\Framework\Controller\ResultFactory;

class Index extends \Magento\Framework\App\Action\Action
{

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        TransportBuilder $transportBuilder,
        array $data = [])
    {
        $this->transportBuilder = $transportBuilder;
        return parent::__construct($context,$data);
    }

    public function execute()
    {
        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);

        try{
            $post = $this->getRequest()->getPostValue();
            $senderEmail = "sender_address@example.com";
            $senderName = "Sender Name";
            $recipientEmail = "receivers_address@example.com";

            $identifier = 1;  // Enter your email template identifier here

            $requestData = array();

            if($post['fname']){
                $requestData['fname'] = $post['fname'];
            }
            if($post['address']){
                $requestData['address'] = $post['address'];
            }
            if($post['city']){
                $requestData['city'] = $post['city'];
            }
            if($post['state']){
                $requestData['state'] = $post['state'];
            }
            // You can add more data as given above

            $postObject = new \Magento\Framework\DataObject();
            $postObject->setData($requestData);

            $transport = $this->transportBuilder
                ->setTemplateIdentifier($identifier)
                ->setTemplateOptions(['area' => \Magento\Framework\App\Area::AREA_FRONTEND, 'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID])
                ->setTemplateVars(['data' => $postObject])
                ->setFrom(['name' => $senderName,'email' => $senderEmail])
                ->addTo([$recipientEmail])
                ->getTransport();
            $transport->sendMessage();

            $this->messageManager->addSuccess(__('Email has been sent successfully.'));
            $resultRedirect->setUrl($this->_redirect->getRefererUrl());
            return $resultRedirect;
        }catch(\Exception $e){
            $this->messageManager->addError(__('Something went wrong. Please try again later.'));
            $resultRedirect->setUrl($this->_redirect->getRefererUrl());
            return $resultRedirect;
        }

    }
}

Add below variables in your email template.

{{depend data.fname}}
{{trans "First Name: %fname" fname=$data.fname}}<br/>
{{/depend}}

{{depend data.address}}
{{trans "Address: %address" address=$data.address}}<br/>
{{/depend}}

{{depend data.city}}
{{trans "City: %city" city=$data.city}}<br/>
{{/depend}}

{{depend data.state}}
{{trans "State: %state" state=$data.state}}<br/>
{{/depend}}

Note: Put the action of your form to above controller.

| improve this answer | |
1

simple sending email for objManager

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
    $transport = $objectManager->create('Magento\Framework\Mail\Template\TransportBuilder'); 
        $templateVars = [
                    'message'    => $str_order,
                    'order_no'    => $str_order_no,
                    'order_status'    => $str_order_status,
                    'order_day'    => $str_order_day,
                    'order_email'    => $str_order_email,
                    'order_product'    => $str_order_product,
                    'order_sku'    => $str_order_sku,
                    'order_namep'    => $str_order_namep,
                    'order_qty'    => $str_order_qty,
                    'order_paym'    => $str_order_paym,
                    'order_grand'    => $str_order_grand
                ];

        $data = $transport
            ->setTemplateIdentifier(6)//get temptate id in your create in backend to use variable in backend you should use this tpye format etc . {{var message}} for message  {{var order_no}} for order id
            ->setTemplateOptions(['area' => \Magento\Framework\App\Area::AREA_FRONTEND, 'store' => 1])
            ->setTemplateVars($templateVars)
            ->setFrom(['name' => 'automate_order_notification','email' => 'magento_back@pa-phone.com'])
            ->addTo(['email_youwant_tosend@outlook.com','email_youwant_tosend@outlook.com'])
            ->getTransport();
        $data->sendMessage();
| improve this answer | |
1

I have shared a link for step by step guide to sending a custom mail from Magento 2 using a module.

Magento 2 Uses \Magento\Framework\Mail\Template\TransportBuilder class for send custom email.

You need to create a simple module and set email_tempaltes.xml file for defining your transaction mail templates.

You can send mail from Adminhtml or Frontend Scope area.

| improve this answer | |
0

I highly recommend you to use this Magento 2 SMTP Extension to send email and display a success message. I have tried and really enjoy it.

Magento 2 SMTP Extension

If you have any problems, feel free to contact with the Customer Support. They are very helpful.

| improve this answer | |

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.