前言
在做毕业设计时, 我需要在注册时 有一个给用户发送邮件的功能的需求。
需要设置smtp服务
我以QQ邮箱举例:
在 设置 -> 账户 找到 POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务
一定要记住你的授权码,待会会用到。
node 引入 nodemailer
首先 ,你需要下载这个插件
$ npm install nodemailer --save
复制代码
配置 nodemailer
// 引用发送邮件插件
const nodeMailer = require('nodemailer')
// 引入证书文件 (获取我的授权码和qq邮箱民)
const credential = require('../config/credentials')
// 创建传输方式
const transporter = nodeMailer.createTransport({
service: 'qq',
auth: {
user: credential.qq.user,
pass: credential.qq.pass // 这个需要你的授权码!!!
}
})
// 注册发送邮件给用户
exports.emailSignUp = function (email, res) {
// 发送信息的内容
let options = {
from: 'xxxxxxx@qq.com', // 这里是你开启SMTP服务的QQ邮箱号
to: email, // 这个是前端注册页面输入的邮箱号
subject: '感谢您在xxxx注册',
html: `<span>xxxx欢迎您的加入!</span>
<a href="http://localhost:8080/">点击</a>`
}
// 发送邮件
transporter.sendMail(options, function (err, msg) {
if (err) {
res.send(err)
// console.log(err)
} else {
res.send('邮箱发送成功!')
// console.log('邮箱发送成功')
}
})
}
复制代码
比如我访问/email就获取
// 注意这里需要下载body-parser 插件才能使用post获取body内容
router.post('/mail',(req,res)=>{
let mail = req.body.mail
// console.log(mail)
emialserve.emailSignUp(mail,res)
// res.send(mail)
})
复制代码
前端代码请求: (使用的uni-app框架)
uni.request({
url: "http://10.200.120.197:3000/mail",
data: {
mail:this.user
},
method: 'POST',
success: (data) => {
console.log(data)
}
})
复制代码
近期评论