I believe you all know that there is a process of receiving verification code during login operation. I have been very interested in this before and often asked students how the verification code works on mobile phones. But now we can still achieve this function without mobile phones.


01 preface

In fact, for mobile phone verification code, generally have to charge, free is generally less, and there will be a number of restrictions. Since we can’t use mobile phone captcha to send, let’s do it in a curvy way.

In fact, it is very simple, as long as we install a third party NPM package can be, this package can realize the mail sending function. This package is called Nodemailer, and let’s test it out.

02 installation nodemailer

Create a new directory, initialize package.json (NPM init) in the root directory, and install nodemailer directly.

npm install nodemailer --save
Copy the code

Then we create a new entry file app.js to test the code.

"use strict";
const nodemailer = require("nodemailer");
const fs = require("fs");
const path = require("path");
let transporter = nodemailer.createTransport({
  // host: 'smtp.ethereal.email',
  service: "qq"./ / use the built-in email transmission check the support list: https://nodemailer.com/smtp/well-known/
  // port: 465, // SMTP port
  secureConnection: true.// SSL is used
  auth: {
    user"[email protected]".pass"xxxxxxxxxxx".// Authorization code, not QQ password}});let mailOptions = {
  from'"alanwu" <[email protected]>'.// Send address
  to: "[email protected]".// Receive list (multiple)
  subject: "Hello,this is alan from China!"./ / theme
  // Send text or HTML (optionally)
  text: 'Hello world! '.// plain text body
  //html: fs.createReadStream(path.resolve(__dirname,'index.html'))
  html: '<img src="cid:01">'.attachments: [                 // Add attachments (multiple)
    {
      filename"image".path: path.resolve(__dirname, "2.jpg"),
      cid"01".// this corresponds to the above image cid
    },
    {
      filename"a.txt".content"hello world!"}, {filename"b.txt".path"./text.txt".// Create a root directory},]};
// Send an email
transporter.sendMail(mailOptions, (error, info) => {
  if (error) {
    return console.log(error);
  }
  console.log(info);
});

Copy the code

So let’s take a look at the service field, and if we do that we don’t have to say host and port. You can have a look at the official introduction, details here. It’s actually packaged for you, very handy.

Partial services

Send plain text text

It is easy to write the text we want to send directly in the text under mailOptions, and the other HTML and attachments need not be configured.


HTML Template sending

Some students may think that the text text is too low, we should write some gorgeous web pages to send. Okay, we can actually customize HTML pages, so instead of using text fields, we’ll use HTML fields and we’re going to import HTML files.

We create a new index.html file in the root directory to send the HTML file to each other, and here I just grab a random web page. Resolve (__dirname,’index.html’)). Run it again and we’ll get the message.


Sending pictures

Instead of sending an HTML file in the HTML field, we can send an HTML: After ‘‘, we write the address of the attachments in the attachments. I place a picture directly under the root directory, and cid needs to be attached to it.

My public number, online attention!

Add attachments

Here we can add some files, such as here I added TXT files, DOCx files, PDF files, ZIP files can be.


03 Verification Code Function

We’re really only interested in the captcha part, so don’t worry about arranging what’s going on here. We first want to find a way to generate a verification code, generally 4-6 bits are ok, the following is a simple method to generate a bar.

let code = Math.random().toString().substr(2.4)// Start from the second position and start from the fourth position.
Copy the code

We’ll just use the text field to send it. The code can be generated at the beginning. In fact, we can have a verification function, let the user input captcha and you generate a comparison is consistent.

text: 'Your verification code is${code}, the captcha will be valid for 10 minutes
Copy the code

Some minor problems

I actually had some problems with the test, but I don’t know why.

  • Error: Message failed: 554 DT:SPM 163

I checked 163’s website and came to the following conclusion:

DT:SPM sends emails that contain unauthorized information or are identified as spam by the system. Check whether any user sends viruses or spams.

This is when I send the picture, which is my TWO-DIMENSIONAL code picture, but I can change a common picture, no solution.

  • Failed to send to multiple users. Procedure

When I tried to write two users in the to field, only one was successful and the other was returned, I don’t know what happened.

05 summary

Ok, so that’s all for this article, but it’s not like there’s anything there that I thought was awesome that I could do with very simple code.

Nodemailer has a lot of properties left unsaid, but I’ll just cover the core of sending emails, which are useful in everyday life, especially for login authentication.

Github address