当前位置: 技术文章>> magento2中的电子邮件模板以及代码示例

文章标题:magento2中的电子邮件模板以及代码示例
  • 文章分类: Magento
  • 2858 阅读
系统学习magento二次开发,推荐小册:《Magento中文全栈二次开发 》

本小册面向Magento2以上版本,书代码及示例兼容magento2.0-2.4版本。涵盖了magento前端开发,后端开发,magento2主题,magento2重写,magento2 layout,magento2控制器,magento2 block等相关内容,带领您成为magento开发技术专家。


在 Magento 2 中,可以使用电子邮件模板来定义发送给客户的电子邮件的格式和内容。电子邮件模板通常包含 HTML 和文本版本,以便适应不同的电子邮件客户端和用户偏好。下面是一个简单的 Magento 2 电子邮件模板的代码示例:



<!-- File: app/code/Custom/Module/view/frontend/email/template.html -->
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>My Custom Email</title>
</head>
<body>
  <p>Dear {{var customer.name}},</p>
  <p>Thank you for your recent purchase. Your order number is {{var order.increment_id}}.</p>
  <p>Here are the details of your order:</p>
  <table>
    <thead>
      <tr>
        <th>Product</th>
        <th>Price</th>
        <th>Qty</th>
        <th>Subtotal</th>
      </tr>
    </thead>
    <tbody>
      {{layout handle="sales_email_order_items" order=$order}}
    </tbody>
    <tfoot>
      <tr>
        <td colspan="3">Subtotal</td>
        <td>{{var order.subtotal|formatPrice}}</td>
      </tr>
      <tr>
        <td colspan="3">Shipping & Handling</td>
        <td>{{var order.shipping_amount|formatPrice}}</td>
      </tr>
      <tr>
        <td colspan="3">Tax</td>
        <td>{{var order.tax_amount|formatPrice}}</td>
      </tr>
      <tr>
        <td colspan="3">Grand Total</td>
        <td>{{var order.grand_total|formatPrice}}</td>
      </tr>
    </tfoot>
  </table>
  <p>Thank you for your business!</p>
</body>
</html>

在上述代码中,使用双括号 {{...}} 的方式插入变量,例如 {{var customer.name}} 和 {{var order.increment_id}},这些变量将在发送电子邮件时自动替换为实际的值。同时,使用 {{layout ...}} 标签可以引用布局文件中定义的块,例如 sales_email_order_items 块用于显示订单中的商品列表。


需要注意的是,在 Magento 2 中,电子邮件模板位于主题文件夹的 Magento_Email 模块中,可以在自定义模块中创建自己的电子邮件模板,例如上述代码示例中的 Custom/Module/view/frontend/email/template.html 文件。可以在 Magento 2 的代码中使用 Magento\Framework\Mail\Template\TransportBuilder 类来构建电子邮件并发送。


推荐文章