Email send in Magento 2

In this blog post i am going to create a new module to send email form magento custom contat form


1. Create email_templates.xml file in app/code/Contact/Us/etc



 <?xml version="1.0"?>  
 <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../Email/etc/email_templates.xsd">  
 <template id="send_email_email_template" label="Email Form" file="email_template.html" type="text" module="[Name_Space]_[Your_Module]" area="frontend"/>  
 </config>  




2. Create email_template.html in app/code/Contact/Us/view/frontend/email




 <?xml version="1.0"?>  
 <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../Email/etc/email_templates.xsd">  
 <template id="send_email_email_template" label="Email Form" file="email_template.html" type="text" module<!--@subject Test Form@-->  
 <!--@vars {  
 "var data.comment":"Test",  
 "var data.email":"Sender Email",  
 "var data.name":"Sender Name"  
 } @-->  
 {{trans "Name: %name" name=$data.name}}  
 {{trans "Email: %email" email=$data.email}}  
 {{trans "Test: %test" test=$data.test}}="[Name_Space]_[Your_Module]" area="frontend"/>  
 </config>  

At this stage you will find your template under admin







3. Create Post.php in app/code/Contact/Us/Controller/Index



 <?php  
 namespace Contact\Us\Controller\Index;  
 class Post extends \Magento\Framework\App\Action\Action  
 {  
   /**  
   * @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;  
   /**  
   * @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  
   */  
   public function __construct(  
     \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  
   ) {  
     parent::__construct($context);  
     $this->_transportBuilder = $transportBuilder;  
     $this->inlineTranslation = $inlineTranslation;  
     $this->scopeConfig = $scopeConfig;  
     $this->storeManager = $storeManager;  
     $this->_escaper = $escaper;  
   }  
   /**  
   * Post user question  
   *  
   * @return void  
   * @throws \Exception  
   */  
   public function execute()  
   {  
     $post = $this->getRequest()->getPostValue();  
     if (!$post) {  
     $this->_redirect('/');  
     return;  
   }  
   $this->inlineTranslation->suspend();  
   try {  
       $recipientMail = $this->getRequest()->getPostValue('email');  
       $postObject = new \Magento\Framework\DataObject();  
       $postObject->setData($post);  
       $error = false;  
       $sender = [  
         'name' => 'xMageStore',  
         'email' => 'support@xmagestore.com'  
       ];  
       $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;  
       $transport = $this->_transportBuilder  
         ->setTemplateIdentifier('send_email_email_template') // 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' => \Magento\Store\Model\Store::DEFAULT_STORE_ID,  
           ]  
         )  
         ->setTemplateVars(['data' => $postObject])  
         ->setFrom($sender)  
         ->addTo($recipientMail)  
         ->getTransport();  
       $transport->sendMessage(); ;  
       $this->inlineTranslation->resume();  
       $this->messageManager->addSuccess(  
       __('Thanks for contacting us. We\'ll respond to you very soon.')  
       );  
       $this->_redirect('/');  
       return;  
     } catch (\Exception $e) {  
       $this->inlineTranslation->resume();  
       $this->messageManager->addError(  
       __('We can\'t process your request right now. Sorry, that\'s all we know.'.$e->getMessage())  
       );  
       $this->_redirect('/');  
       return;  
     }  
   }  
 }  


4. This is the contact form  contact.phtml in my module located under Contact/Us/view/frontend/templates/

 <div class="container">  
      <div class="col-sm-3">  
           &nbsp;  
      </div>  
      <div class="col-md-6">  
           <form class="form contact" action="your_route_id/action/controller" id="xmage-contact-form" method="post" data-hasrequired="* Required Fields" novalidate="novalidate">  
             <fieldset class="fieldset">  
               <legend><h4><span><?= __('Let\'s get to work! Please answer a couple of short questions about you and your project.'); ?></span></h4></legend><br>  
               <div class="field name required">  
                 <label class="label" for="name"><span><?= __('Name'); ?></span></label>  
                 <div class="control">  
                   <input name="name" id="name" title="Name" value="" class="input-text" type="text" data-validate="{required:true}" aria-required="true">  
                 </div>  
               </div>  
               <div class="field email required">  
                 <label class="label" for="email"><span><?= __('Email'); ?></span></label>  
                 <div class="control">  
                   <input name="email" id="email" title="Email" value="" class="input-text" type="email" data-validate="{required:true, 'validate-email':true}" aria-required="true">  
                 </div>  
               </div>  
               <div class="field telephone">  
                 <label class="label" for="telephone"><span><?= __('Phone Number'); ?></span></label>  
                 <div class="control">  
                   <input name="telephone" id="telephone" title="Phone Number" value="" class="input-text" type="text">  
                 </div>  
               </div>  
               <div class="field company_name required">  
                 <label class="label" for="company_name"><span><?= __('Company Name'); ?></span></label>  
                 <div class="control">  
                   <input name="company_name" id="company_name" title="Name" value="" class="input-text" type="text" data-validate="{required:true}" aria-required="true">  
                 </div>  
               </div>  
               <div class="field budget required">  
                 <label class="label" for="name"><span><?= __('What\'s your budget?'); ?></span></label>  
                 <div class="control">  
                      <select class="input-select" name="budget" id="budget" title="Budget" data-validate="{required:true}" aria-required="true">  
                           <option value=""><?= __('what\'s your budget?'); ?></option>  
                           <option value="$500-$1000"><?= __('$500-$1000'); ?></option>            
                           <option value="$1000-$2000"><?= __('$1000-$2000');?></option>  
                           <option value="over $2000"><?= __('over $2000');?></option>  
                      </select>  
                 </div>  
               </div>  
               <div class="field time required">  
                 <label class="label" for="name"><span><?= __('What\'s your time frame?'); ?></span></label>  
                 <div class="control">  
                   <input name="time_frame" id="time_frame" title="Time Frame" value="" class="input-text" type="text" data-validate="{required:true}" aria-required="true">  
                 </div>  
               </div>  
               <div class="field comment required">  
                 <label class="label" for="comment"><span><?= __('Anything else you\'d like us to know?'); ?></span></label>  
                 <div class="control">  
                      <textarea name="comment" id="comment" title="What’s on your mind?" class="input-text" cols="5" rows="3" data-validate="{required:true}" spellcheck="false" aria-required="true"></textarea>  
                 </div>  
               </div>  
                 </fieldset>  
             <div>  
               <div class="primary">  
                 <input type="hidden" name="requestType" id="requestType" value="<?php   
                 if(empty($requestedId)){  
                               echo "HIRE US";  
                          }else{  
                               echo $requestType[$requestedId];  
                          }  
                  ?>">  
                 <button type="submit" title="Submit" class="action submit primary">  
                   <span><?= __('Submit'); ?></span>  
                 </button>  
               </div>  
             </div>  
           </form>  
      </div>  
      <div class="col-sm-3">  
           &nbsp;  
      </div>  
 </div>  
 <script type="text/x-magento-init">  
   {  
     "#xmage-contact-form": {  
       "validation": {}  
     }  
   }  
 </script>  
 

You can also find a email template preview under admin>marketing>email template


here is sample preview of email






Comments

Popular posts from this blog

Jasper report integration in Spring boot/Spring MVC.

FireBase Crud operation in Spring Boot

Hybris Overview and b2c installation initialization