Nodemailer簡介
Nodemailer是一個簡單易用的Node.js郵件發送組件
GitHub地址:https://github.com/nodemailer/nodemailer
Nodemailer的主要特點包括:
- 支持Unicode編碼
- 支持Window系統環境
- 支持HTML內容和普通文本內容
- 支持附件(傳送大附件)
- 支持HTML內容中嵌入圖片
- 支持SSL/STARTTLS安全的郵件發送
- 支持內置的transport方法和其他插件實現的transport方法
- 支持自定義插件處理消息
- 支持XOAUTH2登錄驗證
安裝使用:
1.先下載
npm install nodemailer --save
2.封裝sendEmail.js
這裏我對發送郵件進行了簡單的封裝,用的時候只需要傳參數就好了
const nodemailer = require('nodemailer'); //引入模塊
let transporter = nodemailer.createTransport({
//node_modules/nodemailer/lib/well-known/services.json 查看相關的配置,如果使用qq郵箱,就查看qq郵箱的相關配置
service: 'qq', //類型qq郵箱
port: 465,
secure: true, // true for 465, false for other ports
auth: {
user: '[email protected]', // 發送方的郵箱
pass: 'xxxx' // smtp 的授權碼
}
});
//pass 不是郵箱賬戶的密碼而是stmp的授權碼(必須是相應郵箱的stmp授權碼)
//郵箱---設置--賬戶--POP3/SMTP服務---開啓---獲取stmp授權碼
function sendMail(mail, code, call) {
// 發送的配置項
let mailOptions = {
from: '"Express-demo" <[email protected]>', // 發送方
to: mail, //接收者郵箱,多個郵箱用逗號間隔
subject: '歡迎來到"Express-demo"', // 標題
text: 'Hello world?', // 文本內容
html: '<p>這裏是"Express-demo"詳情請點擊:</p><a href="https://www.jianshu.com/u/5cdc0352bf01">點擊跳轉</a>', //頁面內容
// attachments: [{//發送文件
// filename: 'index.html', //文件名字
// path: './index.html' //文件路徑
// },
// {
// filename: 'sendEmail.js', //文件名字
// content: 'sendEmail.js' //文件路徑
// }
// ]
};
//發送函數
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
call(false)
} else {
call(true) //因爲是異步 所有需要回調函數通知成功結果
}
});
}
module.exports = {
sendMail
}
3.使用方法
const Koa = require('koa');
const app = new Koa();
const Router = require('koa-router');
const router = new Router();
const staticFiles = require('koa-static');
const bodyParser = require('koa-bodyparser');
const cors = require('koa2-cors'); // 解決跨域問題
const email = require('./sendEmail.js'); //引入封裝好的函數
const check = {} //聲明一個對象緩存郵箱和驗證碼,留着
app.use(bodyParser());
app.use(cors());
app.use(staticFiles(__dirname + '/')); //靜態目錄
app.use(async (ctx, next) => { //對於任何請求,app將調用該異步函數處理請求:
await next(); //調用next() 前面要加await
});
router.post('/email', async (ctx, next) => {
const mail = ctx.request.body.email
const code = parseInt(Math.random(0, 1) * 10000) //生成隨機驗證碼
check[mail] = code
if (!mail) {
return ctx.body = '參數錯誤' //email出錯時或者爲空時
}
async function timeout() {
return new Promise((resolve, reject) => {
email.sendMail(mail, code, (state) => {
resolve(state);
})
})
}
await timeout().then(state => {
if (state) {
return ctx.body = "發送成功"
} else {
return ctx.body = "失敗"
}
})
})
app.use(router.routes()).use(router.allowedMethods()) // 啓動路由
app.listen(3002, err => {// 監聽端口、啓動程序
if (err) throw err;
console.log('runing...');
})