如何实如今网页上发邮件功能?方法有不少。若是是本身搭建后台,能够利用express-mailer, Nodemailer
等npm
包;也有更为方便快捷的方法,即最近很火的概念Serverless(无服务器服务),好比阿里云提供的邮件推送服务,直接调用API 便可实现邮件推送;GitHub 上还有利用Google 脚本实现发邮件的方法(github地址)。本文记录了用express
搭建Nodejs 服务以及利用Serverless 分别实现邮件推送功能的两种方法。html
$ npm install express --save
$ npm install 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");
});
复制代码
在前端页面利用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
上述经过express
搭建Nodejs 服务的方式看起来不算太复杂,然鹅若是须要在网页上使用,还需将express
部署到服务器,若是网页协议是https
,则还需解决SSL 证书问题。那么Serverless 的出现则令咱们无需考虑这些问题了。web
fetch
方法中,就能够愉快地发邮件了。综上所述,Express 方法的优势是灵活可控,缺点是较为复杂,成本较高;而利用Google 脚本的方法则更方便快捷,无维护成本,但本方法中的接收方邮箱地址需提早写死在脚本中,不支持在网页上自定义。以上两种方法的优劣对好比下:express
优势 | 缺点 | |
---|---|---|
Express | - 灵活可控 | - 步骤较复杂 - 需必定维护成本 |
Serverless (Google Web App) |
- 方便快捷 - 无维护成本 - 无服务器成本 |
- 接收方邮箱地址需提早写死在脚本中,只适用于向固定邮箱发送邮件的场景 |