📤 Enviar emails desde un modulo PrestaShop

Actualizado: 2024-12-01

PrestaShop usa la clase Mail con el metodo estatico Mail::Send() para enviar emails transaccionales. Los emails se basan en plantillas HTML+TXT ubicadas en mails/{idioma}/ dentro del directorio del modulo.

#Mail::Send() — parametros

Signature y uso de Mail::Send()
php
<?php

// Mail::Send(
//   $idLang,         int    - ID del idioma del destinatario
//   $template,       string - nombre del template (sin extension)
//   $subject,        string - asunto del email
//   $templateVars,   array  - variables disponibles en el template
//   $to,             string - email destinatario
//   $toName,         string - nombre del destinatario (opcional)
//   $from,           string - email remitente (null = PS config)
//   $fromName,       string - nombre remitente (null = PS config)
//   $fileAttachment, array  - adjuntos (null = sin adjuntos)
//   $mode_smtp,      bool   - forzar SMTP (false = configuracion PS)
//   $templatePath,   string - ruta de la plantilla
//   $die,            bool   - lanzar excepcion si falla (false = silencioso)
//   $idShop,         int    - ID tienda para config de email
// )

$result = Mail::Send(
    $this->context->language->id,   // idioma del destinatario
    'mymodule_confirmation',         // nombre del template
    $this->trans('Confirmacion de pedido', [], 'Modules.Mymodule.Shop'),
    [
        '{firstname}' => $customer->firstname,
        '{lastname}'  => $customer->lastname,
        '{order_id}'  => $orderId,
        '{shop_name}' => Configuration::get('PS_SHOP_NAME'),
        '{shop_url}'  => Context::getContext()->link->getBaseLink(),
    ],
    $customer->email,                // destinatario
    $customer->firstname . ' ' . $customer->lastname,  // nombre destinatario
    null,                            // from: usa el configurado en PS
    null,                            // fromName: usa el configurado en PS
    null,                            // sin adjuntos
    false,                           // usar config SMTP de PS
    _PS_MODULE_DIR_ . $this->name . '/mails/' // ruta de plantillas
);

if ($result === false) {
    // El email no pudo enviarse
    $this->logger?->error('Failed to send email to ' . $customer->email);
}

#Crear la plantilla de email

Estructura de plantillas de email en el modulo
bash
modules/mymodule/mails/
├── en/
│   ├── mymodule_confirmation.html  # HTML del email
│   ├── mymodule_confirmation.txt   # Version texto plano
│   └── subject.tpl                 # (opcional) asuntos multilingue
├── es/
│   ├── mymodule_confirmation.html
│   └── mymodule_confirmation.txt
└── fr/
    ├── mymodule_confirmation.html
    └── mymodule_confirmation.txt
mails/es/mymodule_confirmation.html — plantilla HTML basica
html
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>{subject}</title>
</head>
<body>
  <!-- Hereda el layout del tema de email activo -->
  <table width="100%">
    <tr>
      <td>
        <h2>Hola {firstname} {lastname},</h2>
        <p>Tu pedido #{order_id} ha sido confirmado.</p>
        <p>
          <a href="{shop_url}" style="color:#25b9d7;">
            Visitar {shop_name}
          </a>
        </p>
      </td>
    </tr>
  </table>
</body>
</html>

#Email con adjunto

Enviar email con archivo adjunto (PDF, imagen...)
php
<?php

// El parametro $fileAttachment es un array de arrays
$attachment = [
    [
        'content'  => file_get_contents('/ruta/al/archivo.pdf'),  // contenido binario
        'name'     => 'factura-' . $orderId . '.pdf',             // nombre del archivo
        'mime'     => 'application/pdf',                           // MIME type
    ],
];

Mail::Send(
    $idLang,
    'mymodule_invoice',
    'Tu factura ' . $orderId,
    $templateVars,
    $customer->email,
    $customer->firstname,
    null, null,
    $attachment,      // <-- aqui los adjuntos
    false,
    _PS_MODULE_DIR_ . $this->name . '/mails/'
);

#Email multilingue

Enviar email en el idioma del destinatario
php
<?php

// Para enviar en el idioma del cliente (no el activo)
$customer     = new Customer($idCustomer);
$idLangCustomer = (int) $customer->id_lang;  // idioma registrado del cliente

// Verificar que existe la plantilla en ese idioma
$templatePath = _PS_MODULE_DIR_ . $this->name . '/mails/';
$langIso      = Language::getIsoById($idLangCustomer);
$templateFile = $templatePath . $langIso . '/mymodule_confirmation.html';

if (!file_exists($templateFile)) {
    // Fallback al idioma por defecto
    $idLangCustomer = (int) Configuration::get('PS_LANG_DEFAULT');
}

Mail::Send(
    $idLangCustomer,
    'mymodule_confirmation',
    'Confirmacion',
    $templateVars,
    $customer->email,
    $customer->firstname,
    null, null, null, false,
    $templatePath
);
Descargar en Markdown Pensado para pegar en ChatGPT, Claude u otra IA. Incluye solo el contenido de esta pagina.