2

I want to send email using SMTP in Magento2 I tried following code

 public function execute()
{

      $smtpHost = '***.*****.***';
      $to = 'email.com' ? 'email.com' : 'test';
    $smtpConf = array(
        'auth' => 'login',
        'port' => '25',
        'ssl' => 'tls', 
        'username' => 'email.com',
        'password' => '123456'
    );
    $transport = new \Zend_Mail_Transport_Smtp($smtpHost, $smtpConf);
    $from = trim('email@gmai;l.com');
    $mail = new \Zend_Mail();
    $mail->setFrom($from, 'test');
    $mail->addTo($to, $to);
    $mail->setSubject('Hello from MagePal');
    $mail->setBodyText('Thank you for choosing MagePal extension.');
    $result = __('Sent... Please check your email') . ' ' . $to;
    try {
        //only way to prevent zend from giving a error
        if (!$mail->send($transport) instanceof \Zend_Mail){echo $result;}
    } catch (\Exception $e) {
      echo   $result = __($e->getMessage());
    } 

  }

And its working but I want to call transcriptional template how I can call? I have create 1 email template in admin with id 2.

Please let me know how I can call transcriptional email template of SMTP emails.

0

\Magento\Framework\Mail\Template\TransportBuilder is what you need here.

So add a constructor to your class where you inject your dependency:

  private $_transportBuilder;

  public function __construct( 

   \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder

  ){
    $this->_transportBuilder = $transportBuilder;
  }

And then don't use Zend_Mail, generate your template in a separate method:

public function generateTemplate($emailTemplateVariables,$senderInfo,$receiverInfo)
{
    $template =  $this->_transportBuilder->setTemplateIdentifier($this->temp_id)
            ->setTemplateOptions(
                [
                    'area' => \Magento\Framework\App\Area::AREA_FRONTEND, /* here you can defile area and
                                                                             store of template for which you prepare it */
                    'store' => $this->_storeManager->getStore()->getId(),
                ]
            )
            ->setTemplateVars($emailTemplateVariables)
            ->setFrom($senderInfo)
            ->addTo($receiverInfo['email'],$receiverInfo['name']);
    return $this;        
}

and call it in your execute method:

        

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

  

  • Hi It is not working for me:( Can you please explain me how I can send it with SMTP class object? – konika Jul 11 '16 at 9:47

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.