Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

1. Introduction

Recently, I was writing a blog system. In the “comment” module, THERE was a requirement: user 1 had commented and left a message, and user 2 responded to user 1’s comment.

At this point, you need to send an email to inform user 1 that his comment has received a response, so you want to write an automatic email function.

Nodemailer is a simple and easy to use Node.js mail sending component that can use SMTP protocol to send emails from specified accounts.

However, Nodemailer can only run in node. js environment. If you use Nodemailer directly in a browser, an error will be reported. Therefore, my idea is to use express framework to build a simple route in my own “Ali Cloud server” Node.js environment, and “Nodemailer” runs on the server. The front-end page uses Axios to send HTTP requests. After receiving the corresponding requests, the server obtains parameters and sends emails using “Nodemailer”.

Attention should also be paid to the same origin policy.

Without further ado, start implementing such a feature!

2. Client code

The client simply needs to send an HTTP request to the server via Axios:

axios({
    url: 'http://XX.XXX.XXX.XXX:4000/email'.method: 'get'.params: {
        name,
        owner,
        email: replyEmail,
        search: 'msg',},withCredentials: true,
})
    .then(() = > message.success('Reply successful! '))
    .catch(err= > console.error(err));
Copy the code

The withCredentials are set to true, specifying that cookie information is carried when cross-domain requests are involved.

3. Server-side code

With modular routing, all routing requests are handled in app.js, and each module handles the corresponding logic.

In app.js, use() middleware intercepts all requests and sets the header uniformly for RES to address the same-origin restriction.

App. Js:

const express = require('express');
const app = express();
const email = require('./email');

// Intercept all requests
app.use((req, res, next) = > {
    1. Which clients are allowed to access me
    // * allows all clients to access me
    // Note: if cookie information is passed in a cross-domain request, the value cannot be an asterisk (*), such as the specific domain name information
    res.header('Access-Control-Allow-Origin'.'http://localhost:3001');
    // 2. Which request methods are allowed for clients to access me
    res.header('Access-Control-Allow-Methods'.'get,post');
    // Allow clients to send cross-domain requests with cookie information
    res.header('Access-Control-Allow-Credentials'.true);
    next();
});

// Email notification service for blog comments after receiving replies
app.use('/email', email);

app.listen(4000);
console.log('Server started successfully, listening on port 4000... ');
Copy the code

The steps for sending an email are described in email.js and are divided into three main steps:

  1. The introduction ofnodemailer
  2. Create sender information
  3. Send an email

In this case, I use email 163. In email 163, I need to enable the SMTP service and obtain the authorization code.

Email. Js:

const express = require('express');
const email = express.Router();
// 1. Introduce nodemailer
const nodemailer = require('nodemailer');

// 2. Create sender information
const transporter = nodemailer.createTransport({
    host: 'smtp.163.com'.port: 465.secureConnection: true.// use SSL
    auth: {
        user: '[email protected]'.// Your email address
        pass: 'xxxxxxxxxxxxxx'.// Not a password, but an authorization code}}); email.get('/'.(req, res) = > {
    const { name, owner, email: to, search } = req.query;
    const blogUrl = 'xxxxxxxxxxxxxxxxx';
    const html = 'xxxxxxxxxxxxxx';
    const subject = 'Comment reply reminder';
    const from = '" the birds "< [email protected] >';
    const mailOptions = {
        from./ / the sender
        to, / / the recipient
        subject, // The subject of the email
        html, // Email content in HTML format
    };
    // 3. Send an email
    transporter.sendMail(mailOptions, (error, info) = > {
        if (error) return console.log(error);
        console.log(info);
    });
    res.send('Email sent successfully! ');
});

module.exports = email;
Copy the code

4. Send emails

Put the server code on the cloud server and run app.js:

Try to reply to a comment, send an AXIos request, send an email, and the server prints the relevant information:

Email received successfully!