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


  • 2018-04-10 14:59:59

    JS实现数组去重方法总结(六种方法)

    这篇文章给大家总结下JS实现数组去重方法(六种方法),面试中也经常会遇到这个问题。文中给大家引申的还有合并数组并去重的方法,感兴趣的朋友跟随脚本之家小编一起学习吧

  • 2018-04-13 17:28:33

    jsoup 使用总结4--高级用法之 script js 脚本

    大部分时候,我们使用jsoup解析网页的时候,都是直接找到某一类元素,或者按某种selector查询;具体使用方法可以参考jsoup官网文档 那么你有没有实际操作过,查找script js 脚本呢,因为很多时候页面的内容是根据js动态生成的,或者数据是动态变更;那么这个时候,我们只是获取html页面中script js脚本之间的内容。

  • 2018-04-15 12:56:05

    WebView控件之WebSettings各种配置方法源码总结

    WebSettings用于管理WebView状态配置,当WebView第一次被创建时,WebView包含着一个默认的配置,这些默认的配置将通过get方法返回,通过WebView中的getSettings方法获得一个WebSettings对象,如果一个WebView被销毁,在WebSettings中所有回调方法将抛出IllegalStateException异常。

  • 2018-04-16 07:28:10

    android点击事件,第一次无效,第二次才响应的问题

    今天碰到的问题,android的标题栏一个回退button,每次进入的时候第一次点击无效,一直到第二次点击时才响应,然后把代码copy到系统的回退按钮里面,结果每次都能响应,后面想了想,应该跟焦点有关系

  • 2018-04-18 15:56:00

    linux下如何实现mysql数据库每天自动备份定时备份

    备份是容灾的基础,是指为防止系统出现操作失误或系统故障导致数据丢失,而将全部或部分数据集合从应用主机的硬盘或阵列复制到其它的存储介质的过程。而对于一些网站、系统来说,数据库就是一切,所以做好数据库的备份是至关重要的!

  • 2018-04-18 20:44:19

    $(...).live is not a function

    jquery中的live()方法在jquery1.9及以上的版本中已被废弃了,如果使用,会抛出TypeError: $(...).live is not a function错误。