E-Mailing

Configuration page - Backend > Message > Email > Email Settings

Enable email loging instead of sending [only for testing]

<?php $this->config->set('config_mail_mock', true);

Email log found at: storage/log/backend/mail.log

Example of sending an email

<?php
try {
        $mail = new Mail($this->config->get('message_mail_engine')); //smtp
        $mail->parameter = $this->config->get('message_mail_parameter');
        $mail->smtp_hostname = $this->config->get('message_mail_smtp_hostname'); //ssl://smtp.gmail.com
        $mail->smtp_username = $this->config->get('message_mail_smtp_username'); //bdbuzz360@gmail.com
        $mail->smtp_password = html_entity_decode($this->config->get('message_mail_smtp_password'), ENT_QUOTES, 'UTF-8'); //uzqdrnbrshzkxzxp
        $mail->smtp_port = $this->config->get('message_mail_smtp_port'); //465
        $mail->smtp_timeout = $this->config->get('message_mail_smtp_timeout'); //300

        $email = 'techbuzz69@gmail.com';
        $store_email = 'ntechpark24@gmail.com';
        $store_name = 'Phspark';
        $subject = 'This is a test mail';
        $message = 'This is a test message body';


        $mail->setTo($email);
        $mail->setFrom($store_email);
        $mail->setSender(html_entity_decode($store_name, ENT_QUOTES, 'UTF-8'));
        $mail->setSubject(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'));
        $mail->setHtml($message);
        dd($mail->send());

} catch (Exception $e) {
        dd($e->getMessage());
}

HTML message example

<?php
$message  = '<html dir="ltr" lang="' . $this->language->get('code') . '">' . "\n";
$message .= '  <head>' . "\n";
$message .= '    <title>' . $this->request->post['subject'] . '</title>' . "\n";
$message .= '    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' . "\n";
$message .= '  </head>' . "\n";
$message .= '  <body>' . html_entity_decode($this->request->post['message'], ENT_QUOTES, 'UTF-8') . '</body>' . "\n";
$message .= '</html>' . "\n";

Extend Email Sending Module

Suppose we need to send email to a customer(s) from extension/module/message/email/send

here is the example of adding this functionality

Step-01: Add ‘Customers’ item to dropdown list —

[Extension/module/customer/init.php]

$this->email_menu->add('module_customer_email_customer', array('name' => 'customer', 'title' => 'Customers'));

*** here look at the key 'module_customer_email_customerall'
        module = extension type
        customer = extension code
        email = sub-directory name,inside controller
        customer = controllername
        template = controller method

$this->extension->addProperty('email_tag', 'module_customer_email_tag_firstname', array('name' => 'customer', 'title' => 'Customer First Name'), true);

Step-02: Add ‘Controller’ for email template —

[Extension/module/customer/email/customer.php]

<?php
class ControllerModuleCustomerEmailCustomer extends BaseModuleCustomerController
{
        public function template()
        {
                $this->data['user_token'] = $this->userToken();

                $this->data['help_affiliate'] = '';
                $this->data['help_customer'] = '';
                $this->data['entry_customer'] = trans('text_customer');
                $this->data['entry_affiliate'] = trans('text_affiliate');


                $this->response->setOutput($this->loadView('email/customer', $this->data));
        }
}

Step-03: Add Tempate View —

[Extension/module/customer/view/theme/default/template/email/customer.twig]

<div class="form-group row to" id="to-module-customer-email-customer">
  <label class="col-sm-2 control-label" for="input-customer"><span title="{{ help_customer }}">{{ entry_customer }}</span></label>
  <div class="col-sm-10">
    <input type="text" name="customers" value="" placeholder="{{ entry_customer }}" id="input-customer" class="form-control" />
    <div class="card bg-gray p-3 well well-sm" style="height: 150px; overflow: auto;"></div>
  </div>
</div>
<script type="text/javascript"><!--
// Customers
$('input[name=\'customers\']').xautocomplete({
  'source': function(request, response) {
    $.ajax({
      url: 'index.php?route=extension/module/customer/customer/autocomplete&user_token={{ user_token }}&filter_name=' +  encodeURIComponent(request),
      dataType: 'json',
      success: function(json) {
        response($.map(json, function(item) {
          return {
            label: item['name'],
            value: item['customer_id']
          }
        }));
      },
      error: function(xhr, ajaxOptions, thrownError) {
        alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
      }
    });
  },
  'select': function(item) {
    $('input[name=\'customers\']').val('');

    $('#customer' + item['value']).remove();

    $('#input-customer').parent().find('.well').append('<div id="customer' + item['value'] + '"><i class="fa fa-minus-circle"></i> ' + item['label'] + '<input type="hidden" name="customer[]" value="' + item['value'] + '" /></div>');
  }
});

$('#input-customer').parent().find('.well').delegate('.fa-minus-circle', 'click', function() {
  $(this).parent().remove();
});
//--></script>

Step-04: Add API for fetching email list & tag value —

[Extension/module/customer/api/email/customer.php]

<?php
/**
 * Customer Index API Controller Class
 *
 * @package             Module\Customer\Api\Email
 * @author              N1 Software Dev Team
 */
class ControllerModuleCustomerApiEmailCustomer extends BaseModuleCustomerApiController
{
        /**
         * Get Customer Emails
         *
         * @return $response
         */
        public function index()
        {
                try {
                        $json = array();

                        $this->load->model('customer');

                        $emails = array();

                        if (!empty($this->request->post['customer'])) {

                                $page = $this->request->post['page'];

                                $customers = array_slice($this->request->post['customer'], ($page - 1) * 10, 10);

                                foreach ($customers as $customer_id) {
                                        $customer_info = $this->model_customer->getCustomer($customer_id);

                                        if ($customer_info) {

                                                // General
                                                $emails[] = $customer_info['email'];

                                                // For Tag value
                                                $emails[] = array(
                                                        'email' => $customer_info['email'],
                                                        'ids' => array(
                                                                'customer_id' => $customer_info['customer_id'],
                                                        ),
                                                );
                                        }
                                }

                                $email_total = count($emails);
                        }

                        $json['email_total'] = $email_total;

                        $json['emails'] = $emails;

                        $this->response(array('status' => 'Success', 'payload' => $json), REST_Controller::HTTP_OK);

                } catch (\Exception $e) {

                        $this->response(array('status' => 'Failed', 'errorMsg' => $e->getMessage()), REST_Controller::HTTP_BAD_REQUEST);
                }
        }
}
[Extension/module/customer/api/email/tag.php]

<?php
/**
 * Customer Index API Controller Class
 *
 * @package             Module\Customer\Api\Email
 * @author              N1 Software Dev Team
 */
class ControllerModuleCustomerApiEmailTag extends BaseModuleCustomerApiController
{
        public function firstname()
        {
                try {
                        $json = array();

                        if (!isset($this->request->get['id'])) {
                                throw new Exception(trans('error_invalid_request_parameter'));
                        }

                        $customer_id = $this->request->get['id'];

                        $this->load->model('customer');
                        $customer_info = $this->model_customer->getCustomer($customer_id);

                        if (!$customer_info) {
                                throw new Exception(trans('error_customer_not_found'));
                        }

                        $json['value'] = $customer_info['firstname'];

                        $this->response(array('status' => 'Success', 'payload' => $json), REST_Controller::HTTP_OK);

                } catch (\Exception $e) {
                        $this->response(array('status' => 'Failed', 'errorMsg' => $e->getMessage()), REST_Controller::HTTP_BAD_REQUEST);
                }
        }
}