一:我们需要在QQ邮箱—设置—账户—Pop3/Smtp—开启—获取stmp服务
二:我们在后端编写之前,我们需要提前在我们的后端中下载一个依赖包
npm i express nodemailer cors
然后我们在node中后端创建nodemailer.js文件
import nodemailer from 'nodemailer'
let nodeMail = nodemailer.createTransport({
service: 'qq', //类型qq邮箱
port: 465,//上文获取的port
secure: true,//上文获取的secure
auth: {
user: '[email protected]', // 发送方的邮箱,可以选择你自己的qq邮箱
pass: 'xxxxxxxx' // 上文获取的stmp授权码
}
});
export default nodeMail
然后我们在我们的接口文件中编写接口以及引入我们想要使用的方法
import nodeMail from './nodemailer.js'
app.post('/api/email', async (req, res) => {
const email = req.body.email
const code = String(Math.floor(Math.random() * 1000000)).padEnd(6, '0') //生成6位随机验证码
//发送邮件
const mail = {
from: `"月亮前端开发"<[email protected]>`,// 发件人
subject: '验证码',//邮箱主题
to: email,//收件人,这里由post请求传递过来
// 邮件内容,用html格式编写
html: `
<p>您好!</p>
<p>您的验证码是:<strong style="color:orangered;">${code}</strong></p>
<p>如果不是您本人操作,请无视此邮件</p>
`
};
await nodeMail.sendMail(mail, (err, info) => {
if (!err) {
res.json({msg: "验证码发送成功"})
} else {
res.json({msg: "验证码发送失败,请稍后重试"})
}
})
});
三:然后我们在前端React当中创建一个文件。
const test = async () => {
const res = await fetch('/api/email', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: '[email protected]'
})
})
const data = await res.json()
console.log(data)
}
然后我们在我们直接使用这个方法就可以了