start

Qq mailbox is used here, because the qq mailbox permissions are better set up.

Install the module

cnpm i nodemailer -S

Create an SMTP client configuration

// nodemailer const nodemailer = require('nodemailer') // Create an SMTP client configuration const config = {service:"QQ", auth: {//'[email protected]'// The sender's email authorization code can be obtained through QQ email and is not unique pass:'xxxxxxxxxxx'}}Copy the code

Create an SMTP client configuration object

 const transporter = nodemailer.createTransport(config)
Copy the code

Create a recipient object

// Random number of verification codeletCode = math.random ().toString().substr(2, 4) const mail = {// Sender email'Nickname < Sender email >'
     from: `"web"<[email protected]> ', // Subject:'Activation verification code'// The recipient's email address can be other than qq.' '// Here you can add the HTML tag HTML: '<b> Your activation verification code is:${code}, please keep it valid within 24 hours. </b>` }Copy the code

Call transporter.sendMail(mail, callback)

 transporter.sendMail(mail, function(error, info) {
         if (error) {
             return console.log(error);
         }
         transporter.close()
         console.log('mail sent:', info.response)
     })
Copy the code

Qq permission Settings

Finally, you can happily send emails

Full code demo

// nodemailer const nodemailer = require('nodemailer') // CaptCHA random bookletCode = math.random ().toString().substr(2, 4) // Create an SMTP client configuration const config = {service:"QQ", auth: {//'[email protected]'// The sender's email authorization code can be obtained through QQ email and is not unique pass:'xxxxxxxxxxxxxxxxxxxxxx'// After the authorization code is generated, you need to wait for a while before using it. Otherwise, an error will be reported during authentication. But don't panic}} / / create a SMTP client configuration object const from = nodemailer. CreateTransport (config) / / create a recipient object const mail = {/ / the sender email'Nickname < Sender email >'
     from: `"web"<[email protected]> ', // Subject:'Activation verification code'// The recipient's email address can be other than qq.'[email protected]'// Here you can add the HTML tag HTML: '<b> Your activation verification code is:${code}, please keep it valid within 24 hours. </b> '} // Call transporter.sendMail(mail, callback) transporter.sendMail(mail, callback)function(error, info) {
         if (error) {
             return console.log(error);
         }
         transporter.close()
         console.log('mail sent:', info.response)
     })

Copy the code