Appearance
nodejs发送电子邮件
先初始化包文件
npm init -y
npm init -y
安装express
npm i express
npm i express
安装电子邮件库
npm i nodemailer
npm i nodemailer
以QQ邮箱为例,将810作为发送方,905作为接受方
router.js文件
js
const express = require("express");
const router = express.Router();
//nodemailer
const nodemailer = require('nodemailer');
router.get('/getcode',(req,res)=>{
let code = Math.floor(Math.random()*900000)+100000
// console.log(code);
// return;
//建立一个smtp连接
let transporter = nodemailer.createTransport({
host:'smtp.qq.com',
service:'qq',
secureConnection:true,
port:465,
auth:{
user:'810757255@qq.com',
pass:'mvhcqqvlirmkbebb'
}
});
//配置相关参数
let options = {
from:'810757255@qq.com',
to:'905956946@qq.com',
subject:'测试邮箱验证码',
html:`<div style="width: 600px;margin: 30px auto;">
<h1 style="text-align: center;">欢迎注册电子邮箱验证码</h1>
<p style="font-size: 24px;">此次验证码如下:</p>
<strong style="font-size: 20px;display: block;text-align: center;color: red;">${code}</strong>
<p>验证码15分钟有效,请及时输入</p>
<i>此次邮件为系统自动发送请勿回复!若您没有进行注册请忽略。</i>
<p style="text-align: right;">--小洛</p>
</div>`
}
// return;
transporter.sendMail(options,function(err,msg){
if(err){
console.log(err);
}else{
console.log(msg);
res.send(msg);
transporter.close();
}
})
})
module.exports = router;
const express = require("express");
const router = express.Router();
//nodemailer
const nodemailer = require('nodemailer');
router.get('/getcode',(req,res)=>{
let code = Math.floor(Math.random()*900000)+100000
// console.log(code);
// return;
//建立一个smtp连接
let transporter = nodemailer.createTransport({
host:'smtp.qq.com',
service:'qq',
secureConnection:true,
port:465,
auth:{
user:'810757255@qq.com',
pass:'mvhcqqvlirmkbebb'
}
});
//配置相关参数
let options = {
from:'810757255@qq.com',
to:'905956946@qq.com',
subject:'测试邮箱验证码',
html:`<div style="width: 600px;margin: 30px auto;">
<h1 style="text-align: center;">欢迎注册电子邮箱验证码</h1>
<p style="font-size: 24px;">此次验证码如下:</p>
<strong style="font-size: 20px;display: block;text-align: center;color: red;">${code}</strong>
<p>验证码15分钟有效,请及时输入</p>
<i>此次邮件为系统自动发送请勿回复!若您没有进行注册请忽略。</i>
<p style="text-align: right;">--小洛</p>
</div>`
}
// return;
transporter.sendMail(options,function(err,msg){
if(err){
console.log(err);
}else{
console.log(msg);
res.send(msg);
transporter.close();
}
})
})
module.exports = router;
app.js
js
const express = require("express");
const app = express();
const getcoderouter = require('./router/index')
app.use('/',getcoderouter)
app.listen(3000,()=>{
console.log("port 3000");
})
const express = require("express");
const app = express();
const getcoderouter = require('./router/index')
app.use('/',getcoderouter)
app.listen(3000,()=>{
console.log("port 3000");
})