從Express 到Serverless - 在網頁上發郵件的一次實踐

前言

如何實如今網頁上發郵件功能?方法有不少。若是是本身搭建後臺,能夠利用express-mailer, Nodemailernpm包;也有更爲方便快捷的方法,即最近很火的概念Serverless(無服務器服務),好比阿里雲提供的郵件推送服務,直接調用API 便可實現郵件推送;GitHub 上還有利用Google 腳本實現發郵件的方法(github地址)。本文記錄了用express搭建Nodejs 服務以及利用Serverless 分別實現郵件推送功能的兩種方法。html

Express

安裝

$ npm install express --save
$ npm install express-mailer前端

express-mailer 配置

//app.js
var express = require("express");
var mailer = require("express-mailer");
var app = express();

mailer.extend(app, {
    from: "todo-from@163.com", // 你的發送郵箱地址
    host: "smtp.163.com", // hostname
    secureConnection: true, // use SSL, 是否使用SSL
    port: 465, // port for secure SMTP,端口
    transportMethod: "SMTP", // default is SMTP. Accepts anything that nodemailer accepts
    auth: {
        user: "todo-from@163.com", // 你的發送郵箱地址
        pass: "todo-password" // 郵箱密碼
    }
});

app.post("/sendemail", function(req, res) {
    const { name, email, mobile, content } = req.body;

    app.mailer.send(
        "email",
        {
            to: "todo-xxx@163.com", // REQUIRED. 必填,郵件接收方地址
            subject: "Test Email", // REQUIRED. 必填,主題。
            name, // All additional properties are also passed to the template as local variables.
            mobile, 
        },
        function(err) {
            if (err) {
                // handle error,處理錯誤
                res.json({ msg: "Slow network, Try later please" });
                return;
            }
            res.json({ msg: "Email Sent Successfully !" });
        }
    );
});

app.listen(3001, function() {
    console.log("web server listening on port 3001");
});
複製代碼

fetch

在前端頁面利用isomorphic-unfetch來發送fetch請求。node

//sendEmail.js
import fetch from 'isomorphic-unfetch';

//...
const params = { name, mobile };
fetch(
    'http://localhost:3001/sendemail',
    {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: Object.keys(params)
            .map(key => {
                return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
            })
            .join('&')
    }
)
    .then(r => r.text())
    .then(data => {
        const resultData = JSON.parse(data);
        if (resultData.result === 'success') {
            console.log('Send Email Successfully!');
        } else {
            console.log('Slow network, try again later~');
        }
    });
複製代碼

相關問題

  • 若是從req.body中獲取的內容爲空,可使用body-parser中間件
//app.js
var bodyParser = require("body-parser");
app.use(bodyParser.json());
複製代碼
  • 若是遇到跨域問題,可使用cors,詳細配置點擊這裏
//app.js
var cors = require("cors");
app.use(cors());
複製代碼
  • 若是須要設置郵件模板,可使用jade
//app.js
app.set("views", __dirname + "/views");
app.set("view engine", "jade");
複製代碼

而後新增文件夾views,建立模板:git

// views/email.jade

doctype transitional
html
  head
    meta(http-equiv = 'Content-Type', content = 'text/html; charset=UTF-8')
    title= subject
    body
      h1.h1 It's an email from emai-test website. p Name: #{name} p Mobile: #{mobile} 複製代碼

運行

$ node app.jsgithub

Serverless

上述經過express搭建Nodejs 服務的方式看起來不算太複雜,然鵝若是須要在網頁上使用,還需將express部署到服務器,若是網頁協議是https,則還需解決SSL 證書問題。那麼Serverless 的出現則令咱們無需考慮這些問題了。web

send-email-no-server

  • 首先你須要一個gmail 郵箱,郵件是經過該郵箱發送的;
  • 修改Google 腳本,填入接收方郵箱地址;
  • 而後按照步驟操做下來,其實是利用Google 腳本部署了一個Web app。
  • 將部署好的web app 地址填入前端fetch方法中,就能夠愉快地發郵件了。

對比

綜上所述,Express 方法的優勢是靈活可控,缺點是較爲複雜,成本較高;而利用Google 腳本的方法則更方便快捷,無維護成本,但本方法中的接收方郵箱地址需提早寫死在腳本中,不支持在網頁上自定義。以上兩種方法的優劣對好比下:express

優勢 缺點
Express - 靈活可控 - 步驟較複雜
- 需必定維護成本
Serverless
(Google Web App)
- 方便快捷
- 無維護成本
- 無服務器成本
- 接收方郵箱地址需提早寫死在腳本中,只適用於向固定郵箱發送郵件的場景
相關文章
相關標籤/搜索