This article has participated in the activity of “New person creation Ceremony”, and started the road of digging gold creation together.

preface

  • Nodejs/Express server can be used to send a verification code to a mailbox, not only for email registration, but also for various security authentication.

Depend on the package

  • Nodejs server requiresexpressAnd then there’s the package that we send email tonodemailer.corsResolve cross-domain for testing
    npm i express nodemailer cors
    Copy the code

Nodejs server code

  1. First, package nodemail. js file and add the basic configuration. Before configuration, you need to obtain the email type port and secure as well as the email STMP authorization code.

  2. / / node_modules/nodemailer/lib/well – known/services. The json can view the related configuration, such as this is qq mailbox, the port is 465, secure to true.

  1. Email — Set — Account –POP3/SMTP service — Enable — obtain STMP authorization code

//nodemailer.js
import nodemailer from 'nodemailer'

let nodeMail = nodemailer.createTransport({
    service: 'qq'.// Type qq mailbox
    port: 465.// The port obtained above
    secure: true.// Secure obtained above
    auth: {
        user: '[email protected]'.// Sender's email address, you can choose your own QQ email address
        pass: 'xxxxxxxx' // The STMP authorization code obtained above}});export default nodeMail
Copy the code
  1. Introduce what’s writtennodemailer.jsComplete the NodeJS serverapp.js, masterSend E-mailobjectmailProperties of.
 //app.js
 import express from 'express'
 import cors from 'cors'
 import nodeMail from './nodemailer.js'

 const app = express()
 app.use(express.json())
 app.use(cors());
 
 app.post('/api/email'.async (req, res) => {
     const email = req.body.email
     const code = String(Math.floor(Math.random() * 1000000)).padEnd(6.'0') // Generate a random 6-digit verification code
     // Send an email
     const mail = {
         from: 'Moon front Development' 
      
        '
      @qq.com>./ / the sender
         subject: 'Captcha'.// Email subject
         to: email,// The recipient, which is delivered by a POST request
         // The content of the email is written in HTML format
         html: '<p> Hello! </p> <p> Your verification code is: <strong style="color:orangered;" >${code}</strong></p> <p> If you are not the operator, please ignore this message </p> ' 
     };
     await nodeMail.sendMail(mail, (err, info) = > {
         if(! err) { res.json({msg: "Verification code sent successfully"})}else {
             res.json({msg: "Failed to send captcha. Please try again later."})}})}); app.listen(3000.() = > {
     console.log("Service started successfully");
 })
Copy the code

Front-end code testing

<body>
<button onclick="test()">Send E-mail</button>
<script>
    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)
    }
</script>
</body>
Copy the code

Encapsulate their own SMS sending dependency packages

  1. We found this easy to implement, but needed to configure the input content separately, which looked cumbersome.

  2. We might as well encapsulate our own SMS dependency packages. If you are interested, check out my two previous posts:

  • Nodejs NPM Usage Guide (How to publish your own NPM package)
  • Nodejs ES6 module use and ES6 code to ES5 compatibility processing
  1. So I packaged a packagenode-send-email, NPM package address:node-send-email. However, I did not test the compatibility of different mailboxes, and I am interested in sending emails next time. Of course, I also suggest DIY.
npm i node-send-email
Copy the code
// test.js
import sendMail from 'node-send-email'

const test = async() = > {const code = String(Math.floor(Math.random() * 1000000)).padEnd(6.'0') // Generate a random verification code
// The input parameter needed to send mail
    const params = {
        @qq.com, @163.com, @163.com, @163.com
        // The other types can be found in node_modules/node-send-email/service.js.
        type: 'qq'./ / the sender
        name: 'the moon'.// The outbox must be the same as the inbox
        from: '[email protected]'.- Set - Account - POP3/SMTP service - Enable - Obtain STMP authorization code
        smtp: 'xxxxxx'.// The title of the message sent
        subject: 'Captcha'.// The inbox must be the same as the outbox mailbox type
        to: '[email protected]'.// Email content in HTML format
        html: '<p> Hello! </p> <p> Your verification code is: <strong style="color:orangered;" >${code}</strong></p> <p> If you are not the operator, please ignore this message </p> '
    };

    await sendMail.default(params, (result) = > {
        if (result) {
            console.log('Sent successfully')}else {
            console.log('Send failed')
        }
    })
}

test()
Copy the code
> node test.jsSend a successCopy the code

Stern said

If you feel that the article is helpful to you, welcome to like collection oh, there are any mistakes or suggestions can also leave a message, thank you ~