email-templates + mjml 发送邮件

2020-12-07 15:17:45

参考地址 email-templates + mjml 发送邮件

mjml 是一个很不错的响应式邮件html 内容标签库,email-templates 是一个灵活强大的邮件发送框架,两者集成起来我们
可以设计灵活强大的邮件发送系统,以下是一个简单的集成使用,实际使用还有好多地方需要完善

环境准备

  • 项目结构

 

├── README.md
├── app.js
├── package.json
├── polyfill.js
├── templates
│ └── mail.mjml
  • 代码说明
    package.json 项目的依赖以及npm script

 

{
  "name": "email-template-learning",
  "version": "1.0.0",
  "main": "app.js",
  "license": "MIT",
  "dependencies": {
    "email-templates": "^6.1.1",
    "mjml": "^4.5.1",
    "pug": "^2.0.4"
  },
  "scripts": {
    "app":"node app.js"
  }
}

polyfill.js js 字符串插值polyfill,主要解决mjml 对于变量的支持

String.prototype.interpolate = function(params) {
    const names = Object.keys(params);
    const vals = Object.values(params);
    return new Function(...names, `return \`${this}\`;`)(...vals);
}
module.exports = String.prototype.interpolate

app.js 集成email-templates 与mjml 的代码
使用了email-templates 的自定义渲染处理,

 

const Email = require('email-templates');
const mjml2html = require("mjml")
const fs = require("fs")
require("./polyfill")
const email = new Email({
  message: {
    from: 'niftylettuce@gmail.com',
    headers: {
      'X-Some-Custom-Thing': 'Some-Value'
    },
    list: {
      unsubscribe: 'https://niftylettuce.com/unsubscribe'
    }
  },
  transport: {
    jsonTransport: true
  },
  render: (view, locals) => {
    return new Promise((resolve, reject) => {
      // this example assumes that `template` returned
      // is an ejs-based template string
      // view = `${template}/html` or `${template}/subject` or `${template}/text`
     // 集成mjml 的核心部分,读取模版内容,同时应用插值添加变量支持
      if (view.substring("html")) {
        let vars = {
          appname:"dalongdemo-rongfengliang"
        }
        let htmlOutput = mjml2html(fs.readFileSync("templates/mail.mjml").toString().interpolate({vars}))
        resolve(htmlOutput.html)
      }
      if (view.substring("text")) {
        resolve("not support")
      }
    });
  }
}
);

email
  .send({
    template: 'mars',
    message: {
      to: 'elon@spacex.com',
      subject: "demoapp"
    },
    locals: {
      name: 'Elon'
    }
  })
  .then(console.log)
  .catch(console.error);

mail.mjml mjml 模版内容,使用mjml npm 包进行渲染

    <mjml>
  <mj-head>
    <mj-preview>Hello MJML</mj-preview>
    <mj-title>Hello MJML</mj-title>
    <mj-attributes>
      <mj-accordion border="none" padding="1px" />
      <mj-accordion-element icon-wrapped-url="http://i.imgur.com/Xvw0vjq.png" icon-unwrapped-url="http://i.imgur.com/KKHenWa.png" icon-height="24px" icon-width="24px" />
      <mj-accordion-title font-family="Roboto, Open Sans, Helvetica, Arial, sans-serif" background-color="#fff" color="#031017" padding="15px" font-size="18px" />
      <mj-accordion-text font-family="Open Sans, Helvetica, Arial, sans-serif" background-color="#fafafa" padding="15px" color="#505050" font-size="14px" />
    </mj-attributes>
  </mj-head>
  <mj-body>
    <!-- Company Header -->
    <mj-section padding="20px" background-color="#ffffff">
      <mj-column background-color="#dededd">
        <mj-accordion>
          <mj-accordion-element>
            <mj-accordion-title>Why use an accordion?</mj-accordion-title>
            <mj-accordion-text>
              <span style="line-height:20px">
                Because emails with a lot of content are most of the time a very bad experience on mobile, mj-accordion comes handy when you want to deliver a lot of information in a concise way.
              </span>
            </mj-accordion-text>
          </mj-accordion-element>
          <mj-accordion-element>
            <mj-accordion-title>${vars.appname}</mj-accordion-title>
            <mj-accordion-text>
              <span style="line-height:20px">
               ${new Date()} Content is stacked into tabs and users can expand them at will. If responsive styles are not supported (mostly on desktop clients), tabs are then expanded and your content is readable at once.
              </span>
            </mj-accordion-text>
          </mj-accordion-element>
        </mj-accordion>
      </mj-column>
    </mj-section>
    <mj-section background-color="#f0f0f0">
      <mj-column>
        <mj-text font-style="italic" font-size="20px" color="#626262">
         demoappppp
        </mj-text>
      </mj-column>
    </mj-section>

    <!-- Image Header -->
    <mj-section background-url="http://1.bp.blogspot.com/-TPrfhxbYpDY/Uh3Refzk02I/AAAAAAAALw8/5sUJ0UUGYuw/s1600/New+York+in+The+1960's+-+70's+(2).jpg" background-size="cover" background-repeat="no-repeat">

      <mj-column width="600px">

        <mj-text align="center" color="#fff" font-size="40px" font-family="Helvetica Neue">Slogan here</mj-text>

        <mj-button background-color="#F63A4D" href="#">
          Promotion
        </mj-button>

      </mj-column>

    </mj-section>

    <!-- Introduction Text -->
    <mj-section background-color="#fafafa">
      <mj-column width="400px">

        <mj-text font-style="italic" font-size="20px" font-family="Helvetica Neue" color="#626262">My Awesome Text</mj-text>

        <mj-text color="#525252">
          Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin rutrum enim eget magna efficitur, eu semper augue semper. Aliquam erat volutpat. Cras id dui lectus. Vestibulum sed finibus lectus, sit amet suscipit nibh. Proin nec commodo purus. Sed eget nulla elit. Nulla aliquet mollis faucibus.
        </mj-text>

        <mj-button background-color="#F45E43" href="#">Learn more</mj-button>

      </mj-column>
    </mj-section>
    <mj-section>
      <mj-column>
        <mj-carousel>
          <mj-carousel-image src="https://www.mailjet.com/wp-content/uploads/2016/11/ecommerce-guide.jpg" />
          <mj-carousel-image src="https://www.mailjet.com/wp-content/uploads/2016/09/3@1x.png" />
          <mj-carousel-image src="https://www.mailjet.com/wp-content/uploads/2016/09/1@1x.png" />
        </mj-carousel>
      </mj-column>
    </mj-section>
    <!-- 2 columns section -->
    <!-- Side image -->
    <mj-section background-color="white">

      <!-- Left image -->
      <mj-column>
        <mj-image width="200px" src="https://designspell.files.wordpress.com/2012/01/sciolino-paris-bw.jpg" />
      </mj-column>

      <!-- right paragraph -->
      <mj-column>
        <mj-text font-style="italic" font-size="20px" font-family="Helvetica Neue" color="#626262">
          Find amazing places
        </mj-text>

        <mj-text color="#525252">
          Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin rutrum enim eget magna efficitur, eu semper augue semper. Aliquam erat volutpat. Cras id dui lectus. Vestibulum sed finibus lectus.</mj-text>

      </mj-column>
    </mj-section>
    <!-- Icons -->
    <mj-section background-color="#fbfbfb">
      <mj-column>
        <mj-image width="100px" src="http://191n.mj.am/img/191n/3s/x0l.png" />
      </mj-column>
      <mj-column>
        <mj-image width="100px" src="http://191n.mj.am/img/191n/3s/x01.png" />
      </mj-column>
      <mj-column>
        <mj-image width="100px" src="http://191n.mj.am/img/191n/3s/x0s.png" />
      </mj-column>
    </mj-section>
    <!-- Social icons -->
    <mj-section background-color="#e7e7e7">
      <mj-column>
        <mj-social>
          <mj-social-element name="facebook" />
        </mj-social>
      </mj-column>
    </mj-section>
  </mj-body>
</mjml>

 

 

运行&&效果

默认运行的模式是预览,我们可以方便的查看发送内容

  • 运行

yarn app
  • 效果

 

 

说明

以上是一个简单的集成,email-templates 以及mjml 还是很强大的

参考资料

https://github.com/forwardemail/email-templates
https://github.com/mjmlio/mjml
https://github.com/rongfengliang/email-templates-mjml-learning


  • 2020-12-08 17:13:57

    nvm卸载、安装node和npm

    1、node.js、nvm、 npm (1)在cmd中输入`where node`找到node长须所在位置进行删除 (2)确保计算机-环境变量删除相关引用 (3)在cmd中输入`node -v` ,得到以下结果,删除成功

  • 2020-12-08 17:23:36

    Window下完全卸载删除Nodejs

    1.从卸载程序卸载程序和功能。 2.重新启动(或者您可能会从任务管理器中杀死所有与节点相关的进程)。 3.寻找这些文件夹并删除它们(及其内容)(如果还有)。根据您安装的版本,UAC设置和CPU架构,这些可能或可能不存在:

  • 2020-12-09 08:48:45

    nodejs版本以及其对应的npm版本

    正在寻找某个大版本的最新版? Node.js 10.x Node.js 8.x Node.js 6.x Node.js 4.x Node.js 0.12.x Node.js 0.10.x 所有版本

  • 2020-12-12 17:27:54

    手把手教你 GitLab 的安装及使用

    GitLab:是一个基于Git实现的在线代码仓库托管软件,你可以用gitlab自己搭建一个类似于Github一样的系统,一般用于在企业、学校等内部网络搭建git私服。