Use React+node to bind QQ mailbox and send verification code to QQ mailbox

1: We need to go to QQ Mailbox—Settings—Account—Pop3/Smtp—Enable—Get stmp service

Insert image description here

Two: Before we write in the backend, we need to download a dependency package in our backend in advance

npm i express nodemailer cors

Then we create the nodemailer.js file in the backend of node

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

Then we write the interface in our interface file and introduce the methods we want to use

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: "验证码发送失败,请稍后重试"})
         }
     })
 });

Three: Then we create a file in the front-end 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)
    }

Then we can use this method directly

Guess you like

Origin blog.csdn.net/qq_53509791/article/details/129701847