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-12-05 15:11:18

    为什么 Objective-C非常难

    作为一个Objective-C的coder,我总能听到一部 分人在这门语言上抱怨有很多问题。他们总在想快速学习这门语言来写一个App出来,但他们也总是联想到Objective-C看上去实在太难了或者在想这 些语法符号都是神马玩意?不错,他们问得非常好,所以本人也解释一下为什么很多程序员相比较学习Ruby或者Java很容易,但在决定开发iOS或者OS X应用时会那么犹豫。

  • 2018-12-05 15:22:23

    十分钟让你明白Objective-C的语法(和Java、C++的对比)

    很多想开发iOS,或者正在开发iOS的程序员以前都做过Java或者C++,当第一次看到Objective-C的代码时都会头疼,Objective-C的代码在语法上和Java, C++有着很大的区别,有的同学会感觉像是看天书一样。不过,语言都是相通的,有很多共性。下面列出Objective-C语言的语法和Java,C++的对比,这样你就会很容易Objective-C的语法是怎么回事了。

  • 2018-12-05 15:33:33

    一篇文章看懂有关iOS开发语言的一切!

    OS开发语言有哪些?OS开发语言主要包括什么?iOS开发语言具体怎么学习?今天重点介绍一下: iOS开发语言主要包括:C语言基础、Obiective-C编程、Swift、UIKit框架详解这几大块,在这里项目阶段就不详细的介绍了。 C语言基础 C语言是开发语言的基础,是最常用的一门程序设计语言,最常用于编写计算机程序。

  • 2018-12-06 10:03:36

    定时杀掉processlist sleep状态的线程

    由于程序设计的Bug,导致目前这个项目使用的数据库中有很多Sleep状态的线程。找了很多解决办法,还没发现最终有效的解决方案。只能临时使用如下方法: 编写shell文件,如killSleepProcess.sh

  • 2018-12-07 08:26:37

    mysql线程池和连接池的区别

    可能有的DBA会把线程池和连接池混淆,其实两者是有很大区别的,连接池一般在客户端设置,而线程池是在DB服务器上配置;另外连接池可以取到避免了连接频繁创建和销毁,但是无法取到控制MySQL活动线程数的目标,在高并发场景下,无法取到保护DB的作用。比较好的方式是将连接池和线程池结合起来使用。 作者:飞鸿无痕 链接:https://www.jianshu.com/p/88e606eca2a5 來源:简书 简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

  • 2018-12-07 17:47:24

    linux中wc命令用法

    Linux系统中的wc(Word Count)命令的功能为统计指定文件中的字节数、字数、行数,并将统计结果显示输出。