0

I am using Magento 2.2.2

I have one form on my website with the fields "Name" and "Email". Now when the customer submits the form I want to send an email to the email address filled by the customer.

I want to send custom HTML in this email and this HTML includes images. How can I achieve this?

I have used below code:

<form class="form"  method="post" name="form_1" id="form_1" enctype="multipart/form-data">

    <div class="formdiv">
        <h2>Custom Form</h2>
    </div>

    <label>Name</label>
    <input type="text" id="name" name="name" required="required" placeholder="Enter Your Name" />

    <label>Email</label>
    <input type="email" id="email_share" name="email_share" required="required" placeholder="Enter Your Email" />

    <input type="submit" id="submit_result" name="submit_result" value="Submit">
</form>
<?php
if(isset($_POST['submit_result']))
{


$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
$to = "[email protected]";
$nameTo = $_POST['txtname'];
$transport = $objectManager->create('Magento\Framework\Mail\Template\TransportBuilder'); 
$data = $transport
    ->setTemplateIdentifier(7)
    ->setTemplateOptions(['area' => \Magento\Framework\App\Area::AREA_FRONTEND, 'store' => 1])
    ->setFrom(['name' => 'Test','email' => '[email protected]'])
    ->addTo($to,$nameTo)
    ->getTransport();
$data->sendMessage();



}
?>

And below as well:

<form class="form"  method="post" name="form_1" id="form_1" enctype="multipart/form-data">

    <div class="formdiv">
        <h2>Custom Form</h2>
    </div>

    <label>Name</label>
    <input type="text" id="name" name="name" required="required" placeholder="Enter Your Name" />

    <label>Email</label>
    <input type="email" id="email_share" name="email_share" required="required" placeholder="Enter Your Email" />

    <input type="submit" id="submit_result" name="submit_result" value="Submit">
</form>
<?php
if(isset($_POST['submit_result']))
{

$to = "[email protected]";
$nameTo = $_POST['txtname'];
$from = "[email protected]";
$nameFrom = "test";

$body ="<table cellpadding='4' cellspacing='0' style='border-collapse:collapse' width='500' border='1'>";
$body.="<tr><td align='left' colspan='2' style='background:#CCC;'><strong>Test email</strong></td></tr>";
$body.="<tr><td width='150' align='left'>Name</td><td align='left'>".$_POST['name']."</td></tr>";
$body.="<tr><td width='150' align='left'>Email</td><td align='left'>".$_POST['email_share']."<br /></td></tr>"; 
$body.="</table>";

$email = new \Zend_Mail();
$email->setSubject("Test Request");
$email->setBodyHtml($body); 
$email->setFrom($from, $nameFrom);
$email->addTo($to, $nameTo);
$email->send();     


}
?>

I have tried both logics but they are not working

3
  • Are you using controller for this feature?
    – Sumit
    Commented Aug 30, 2019 at 5:39
  • Everyone, I have edited my question. Please check Commented Aug 30, 2019 at 6:06
  • You can create a module for this, instead of using $objectManager directly in your phtml file.
    – Sumit
    Commented Aug 30, 2019 at 6:12

4 Answers 4

3

Try below code:

{{Namespace}}/{{Module Name}}/etc/email_templates.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../Email/etc/email_templates.xsd">
    <template id="custom_email_template" label="Email Form" file="custom_email.html" type="html" module="Your_ModuleName" area="frontend"/>
</config>

{{Namespace}}/{{Module Name}}/Controller/yourcontroller.php

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

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


    public function __construct(
        ...
        ...
        \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        ...
        ...
    )
    {
        ...
        ...
        $this->_transportBuilder = $transportBuilder;
        $this->_storeManager     = $storeManager;
        ...
        ...
    }

    public function YourCustomFuction($email,$name){
        $store = $this->_storeManager->getStore()->getId();
        $template   = "custom_email_template";

        /* Receiver Detail  */
        $receiverInfo = [
        'name' => $name,
        'email' => $email,
        ];


        /* Sender Detail  */
        $senderInfo = [
            'name' => 'XYZ',
            'email' => '[email protected]',
        ];

        $this->_transportBuilder->setTemplateIdentifier($template);
        $transport = [
            'name'           => $name,
            'email'           => $email,
        ];
        $this->_transportBuilder->setFrom($senderInfo);
        $this->_transportBuilder->addTo($receiverInfo['email'],$receiverInfo['name']);
        $this->_transportBuilder->setTemplateVars($transport);
        $this->_transportBuilder->setTemplateOptions(['area' => \Magento\Framework\App\Area::AREA_FRONTEND, 'store' => $store]);
        $transport = $this->_transportBuilder->getTransport();
        $transport->sendMessage();


    }

{{Namespace}}/{{Module Name}}/view/frontend/email/custom_email.html

<!--@subject {{var name}}, Your subject line @-->

<p>Your custom email content here</p>

I hope it will help...!!!

3

I've done this by creating below post controller for the custom form to send data with attachment in Magento 2.

<?php

namespace Vendor\Module\Controller\Index;

use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Backend\App\Action;
use Magento\Framework\Filesystem;

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

    const XML_PATH_EMAIL_RECIPIENT = 'rga/email/recipient_email';
    const XML_PATH_EMAIL_SENDER = 'rga/email/sender_email_identity';
    const XML_PATH_EMAIL_TEMPLATE = 'rga/email/email_template';


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

    /**
     * @var \Magento\Framework\Translate\Inline\StateInterface
     */
    protected $inlineTranslation;

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

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

    /**
     * @var \Magento\Framework\Escaper
     */
    protected $_escaper;

    /**
     * @var \Magento\Framework\File\UploaderFactory
     */
    protected $uploaderFactory;

    /**
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder
     * @param \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param \Magento\MediaStorage\Model\File\UploaderFactory $uploaderFactory
     */
    public function __construct(
        Filesystem $filesystem,
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder,
        \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\Escaper $escaper,
        \Magento\MediaStorage\Model\File\UploaderFactory $uploaderFactory
    ) {
        parent::__construct($context);
        $this->_mediaDirectory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA);
        $this->_transportBuilder = $transportBuilder;
        $this->inlineTranslation = $inlineTranslation;
        $this->scopeConfig = $scopeConfig;
        $this->storeManager = $storeManager;
        $this->_escaper = $escaper;
        $this->uploaderFactory = $uploaderFactory;
    }

    /**
     * Post user question
     *
     * @return void
     * @throws \Exception
     */
    public function execute()
    {
        $post = $this->getRequest()->getPostValue();
        if (!$post) {
            $this->_redirect('*/*/');
            return;
        }

        $this->inlineTranslation->suspend();
        try {
            $postObject = new \Magento\Framework\DataObject();
            $postObject->setData($post);

            $error = false;
            if (!\Zend_Validate::is(trim($post['name']), 'NotEmpty')) {
                $error = true;
            }

            $photos = array();
            foreach ($_FILES['photo']['name'] as $key => $image) {

                if (empty($image)) {
                    continue;
                }

                $fileName = '';
                if (isset($_FILES['photo']['name'][$key]) && $_FILES['photo']['name'][$key] != '') {
                    try {
                        $target = $this->_mediaDirectory->getAbsolutePath('rga');
                        $fileName = $_FILES['photo']['name'][$key];
                        $fileExt = strtolower(substr(strrchr($fileName, "."), 1));

                        $fileNamewoe = rtrim($fileName, $fileExt);

                        $fileName = preg_replace('/[^A-Za-z0-9\-]/', '', $fileNamewoe) . time() . $key . '.' . $fileExt;
                        if (!in_array($fileExt, array('jpg', 'jpeg', 'png', 'gif'))) {
                            $this->messageManager->addError(__('Only jpg, jpeg, png and gif file types are allowed.'));
                            session_write_close();
                            $this->_redirect('*/*/');
                            return;
                        }
                        array_push($photos, $fileName);
                        $uploader = $this->uploaderFactory->create(['fileId' => 'photo['.$key.']']);
                        $uploader->setAllowedExtensions(['jpg', 'jpeg', 'png', 'gif']);
                        $uploader->setAllowRenameFiles(false);
                        $uploader->setFilesDispersion(false);
                        $uploader->save($target,$fileName);
                    } catch (Exception $e) {
                        $error = true;
                    }
                }
            }

            if ($error) {
                $this->messageManager->addError(__('Unable to submit your request. Please, try again later'));
                session_write_close();
                throw new \Exception();
            }

            $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
            $transport = $this->_transportBuilder
                ->setTemplateIdentifier($this->scopeConfig->getValue(self::XML_PATH_EMAIL_TEMPLATE, $storeScope)) // this code we have mentioned in the email_templates.xml
                ->setTemplateOptions(
                    [
                        'area' => \Magento\Framework\App\Area::AREA_FRONTEND, // this is using frontend area to get the template file
                        'store' => $this->storeManager->getStore()->getId(),
                    ]
                )
                ->setTemplateVars(['data' => $postObject])
                ->setFrom($this->scopeConfig->getValue(self::XML_PATH_EMAIL_SENDER, $storeScope))
                ->setReplyTo($post['EmailAddress'])
                ->addTo($this->scopeConfig->getValue(self::XML_PATH_EMAIL_RECIPIENT, $storeScope));

            /* add photos to attachment; */
            foreach($photos as $pic) {
                $attachmentFilePath = $this->_mediaDirectory->getAbsolutePath('rga').'/'. $pic;
                if(file_exists($attachmentFilePath)){
                    $transport->addAttachment(file_get_contents($attachmentFilePath,$pic));
                }
            }

            $transport = $transport->getTransport();           
            $transport->sendMessage(); 
            $this->inlineTranslation->resume();
            $this->messageManager->addSuccess(
                __('Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us.')
            );
            $this->_redirect('*/*/');
            return;
        } catch (\Exception $e) {
            $this->inlineTranslation->resume();
            $this->messageManager->addError(
                __('Unable to submit your request. Please, try again later.')
            );
            $this->_redirect('*/*/');
            return;
        }
    }
}

For whole module with email template, you can follow the below artice

https://www.brainacts.com/blog/magento-2-how-to-send-email-programmatically

Hope it helps!!!

2
  • 1
    Your answer is right and appropriate as well +1 for that Commented Nov 28, 2019 at 5:53
  • 1
    @MuhammadHasham Thank you for appreciation.
    – Sumit
    Commented Nov 28, 2019 at 5:56
2

Let's assume your custom html is

/app/code/VendorName/ModuleName/view/frontend/email/modulename/test.html

<div>

Hello, this is a test email.

</div>

Declare your email template, create xml file /app/code/VendorName/ModuleName/etc/email_templates.xml

with content:

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

Finally, create a function to send your email. I am using a controller action. Create file:

/app/code/VendorName/ModuleName/Controller/Index/Sendemail.php

with content:

<?php

namespace VendorName\ModuleName\Controller;

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()
    {
        $store = $this->_storeManager->getStore()->getId();
        $transport = $this->_transportBuilder->setTemplateIdentifier('modulename_test_template')
            ->setTemplateOptions(['area' => 'frontend', 'store' => $store])
            ->setTemplateVars(
                [
                    'store' => $this->_storeManager->getStore(),
                ]
            )
            ->setFrom('general')
            // you can config general email address in Store -> Configuration -> General -> Store Email Addresses
            ->addTo('[email protected]', 'Customer Name')
            ->getTransport();
        $transport->sendMessage();
        return $this;
    }
}

I hope this will help

2
  • I have a custom form in .phtml file in the theme folder. So how can I call execute function when the customer clicks on submit button? Commented Aug 30, 2019 at 5:57
  • @ChintanKaneriya your form is definitely going to request on some controller then in that case add my controller code in your target controller like $transportBuilder and $storeManager in your controller __construct and use it like I did Commented Aug 30, 2019 at 6:00
2

If you are doing via only phtml than try with php mail function. This is the basic way to send mail.

$to = "[email protected]";
$nameTo = $_POST['txtname'];
$from = "[email protected]";
$email_subject = "Test mail";
$body ="<table cellpadding='4' cellspacing='0' style='border-collapse:collapse' width='500' border='1'>";
$body.="<tr><td align='left' colspan='2' style='background:#CCC;'><strong>Test email</strong></td></tr>";
$body.="<tr><td width='150' align='left'>Name</td><td align='left'>".$_POST['name']."</td></tr>";
$body.="<tr><td width='150' align='left'>Email</td><td align='left'>".$_POST['email_share']."<br /></td></tr>"; 
$body.="</table>";

$headers = 'From: '.$from."\r\n".
'Reply-To: '.$from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($to, $email_subject, $body, $headers);
1
  • 1
    Nice and precise answer +1 for that Commented Nov 28, 2019 at 6:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.