preface

Since I need to add friend chains to my website recently, and I don’t want to change static files every time, I have pulled out a form and prepared to fill in my information for everyone to submit to the background for review. However, I need an email to inform everyone that the review has been approved, so I need a plug-in nodemailer[0] for email. Of course the big boys already know. Because usually node play less, so also here to record

Let’s start with the renderings

What happened to that clickbait, regular E-mail to your girlfriend romance? We’re not in a hurry, are we? As discussed later, we will try to use nodemailer step by step ourselves

The preparatory work

We will need an SMTP authorization code to send mail! We need to go to the mailbox to get it, and I choose QQ mailbox here (because the tutorial I found is QQ).

  1. Enter QQ mailbox

  1. Select the account

  1. Turn to POP3 / IMAP/SMTP/Exchange/CardDAV/CalDAV service

  1. Enable POP3/SMTP service

  1. Send information for verification

  1. Copy authorization code

configuration

Stop is here. Don’t ski too fast

Create a folder

Name of the catalog, please

Create entry file

I’ll call it app.js as you please

Initialize the

npm init -y
Copy the code

The installation

npm install nodemailer
Copy the code

Nodemailer is installed in version 4.4.0

package.js

It’s going to look like this when it’s done

{
  "name": "nodeMailDemo"."version": "1.0.0"."description": ""."main": "app.js"."scripts": {
    "test": "echo \"Error: no test specified\" && exit 1".// dev this is the old yan added
    "dev":"node app.js"
  },
  "keywords": []."author": ""."license": "ISC"."dependencies": {
    "nodemailer": "^ 4.4.0"}}Copy the code

come baby

Look at the blackboard, now this is the point, focus on getting into app.js

The introduction of

const nodemailer = require('nodemailer'); 
Copy the code

create

// Create the nodemailer configuration
let transporter = nodemailer.createTransport({
    / / support list: https://nodemailer.com/smtp/well-known/
    service: 'QQ'.// Lao Yan uses QQ
    port: 465.// SMTP port is not needed
    secureConnection: true.auth: {
        user: 'Your email @qq.com'.pass: 'Fill in the SMTP authorization code we just obtained',}});Copy the code

Send content

let mailOptions = {
    from: '"NickName" < http://qq.com >'.to: 'Recipient's Mailbox'.subject: 'Post title', /
    text: 'Fill in what you sent here.'
    // HTML :' I can write HTML here '
};
Copy the code

Perform send

transporter.sendMail(mailOptions, (error, info) = > {
    if (error) {
        return console.log(error);
    }
    console.log('Email sent successfully ID:', info.messageId);
});
Copy the code

Does 20 or so lines of code really work?

node app.js
Copy the code

Old Yan configuration

const nodemailer = require('nodemailer'); // A node plug-in to send mail
function sendEmail (data){
    let transporter = nodemailer.createTransport({
        service: 'QQ'./ / the sender email, support list: https://nodemailer.com/smtp/well-known/
        port: 465./ / SMTP port
        secureConnection: true.// SSL secure links
        auth: {   // The sender's account password
            user: '[email protected]'./ / account
            pass: 'SMTP Authorization Code'.// SMTP authorization code, which can be obtained from email Settings}});let mailOptions = {
        from: 'Sad Diary' <[email protected]>'.// Sender's nickname and address
        to: data.email, // The recipient's email address
        subject: Friends' sad diary | chain exchange request audit results'.// The subject of the message
        html: data.content
    };
    // Send an email
    transporter.sendMail(mailOptions, (error, info) = > {
        if (error) {
            return console.log(error);
        }
        console.log('Email sent successfully ID:', info.messageId);
    }); 
}
// nickName, createTime, link is dynamically filled with parameters returned by the API
let nickName, createTime, link;
nickName =  'Mr. Yan's Blog'
createTime = 'the 2021-01-26 15:20';
link = 'http://blog.lovemysoul.vip'

let data = {
    email:'[email protected]'.content:`<img style="width:100px;" src="http://blog.lovemysoul.vip/favicon.ico" alt="logo"/> <p style="text-indent: 2em;" > dear${ nickName }</p> <p style="text-indent: 2em;" > you in${ createTime }To apply for the${ link }Exchange friend chain has been approved! It has been automatically created! Can travel to < a href = "http://blog.lovemysoul.vip/Friendship.html" > sad diary < / a > to look at it. Thank you for your support! </p> <p style="text-indent: 2em;" Word-wrap: break-word! Important;" > <p style="text-align: right; <p style=" max-width: 100%; clear: both; min-height: 1em; SRC = "http://blog.lovemysoul.vip/_assets/beishang.0aa26ed3.jpg" Alt = "qr code" number public srcset = "" > `
}
sendEmail(data) 
Copy the code

Perform send

node app.js
# or 
npm run dev
Copy the code

Di~ received!

Open on see

Start scheduled Task

Because after we finish sending the email, the task has been closed after execution. We need a scheduled task to keep it running node-schedule

The installation

npm install node-schedule
Copy the code

use

/ / introduction
var schedule = require('node-schedule');
// Execute on time
schedule.scheduleJob('10 * * * * *'.() = >{
    sendEmail(data)
});
Copy the code

The schedule on

Quoting a blogger’s explanation of Nodejs Study Notes (12) — Node-Schedule [2]

* * * * * * ┬ ┬ ┬ ┬ ┬ ┬ │ │ │ │ │ | │ │ │ │ │ └ day of week (0 to 7) (0 or 7 is Sun │ │ │ │ └ ─ ─ ─ ─ ─ the month (1-12) │ │ │ └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ day of the month (1-31) │ │ └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ the adrenaline-charged (0-23) │ └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ minute (0-59) └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ the second (0 to 59, OPTIONAL) 6 placeholder respectively from left to right: Seconds, minutes, hours, days, months, and days of the week '*' is a wildcard, matching any. If seconds is '*', any number of seconds are triggered. Other analogs can be used to see what the following parameters mean: '30 1 * * * *' Trigger at 1:1:30 am every day: '30 1 1 * * *' Trigger at 1:1:30 am on the 1st day of each month: '30 1 1 1 * *' Trigger at 1:1:30 am on the 1st day of January 2016: '30 1 1 1 2016 *' Weekly 1 trigger at 1:1:30: '30 1 1 * * 1'Copy the code

We’re doing 10 seconds per minute to send an email

You can also modify it according to your own needs

Take a look at your email

All the code

const nodemailer = require('nodemailer'); // A node plug-in to send mail
var schedule = require('node-schedule');

function sendEmail (data){
    let transporter = nodemailer.createTransport({
        service: 'QQ'.port: 465.secureConnection: true.auth: {  
            user: '[email protected]'.pass: 'Authorization Code',}});let mailOptions = {
        from: 'Sad Diary' <[email protected]>'.to: data.email, 
        subject: Friends' sad diary | chain exchange request audit results'.html: data.content
    };
    transporter.sendMail(mailOptions, (error, info) = > {
        if (error) {
            return console.log(error);
        }
        console.log('Email sent successfully ID:', info.messageId);
    }); 
}
let nickName, createTime, link ;
nickName =  'Mr. Yan's Blog'
createTime = 'the 2021-01-26 15:20';
link = 'http://blog.lovemysoul.vip'

let data = {
    email:'[email protected]'.content:`<img style="width:100px;" src="http://blog.lovemysoul.vip/favicon.ico" alt="logo"/> <p style="text-indent: 2em;" > dear${ nickName }</p> <p style="text-indent: 2em;" > you in${ createTime }To apply for the${ link }Exchange friend chain has been approved! It has been automatically created! Can travel to < a href = "http://blog.lovemysoul.vip/Friendship.html" > sad diary < / a > to look at it. Thank you for your support! </p> <p style="text-indent: 2em;" Word-wrap: break-word! Important;" > <p style="text-align: right; <p style=" max-width: 100%; clear: both; min-height: 1em; SRC = "http://blog.lovemysoul.vip/_assets/beishang.0aa26ed3.jpg" Alt = "qr code" number public srcset = "" > `
}

schedule.scheduleJob('10 * * * * *'.() = >{
    sendEmail(data)
});
Copy the code

Looking for a little romance for your girlfriend?

All the others in front? Want to play this that is not easy, continue to find wheels, Old Yan found a perfect demo on GitHub effective

Demo: github.com/Vincedream/…

Directly clone

git clone https://github.com/Vincedream/NodeMail.git
&
cd NodeMail
Copy the code

Install dependencies

npm install
Copy the code

Modifying a Configuration File

Go to the root directory main.js and modify the configuration we just talked about after filling in everything

node main.js
Copy the code

Pay attention to the startDay and local variables, remember to modify, or I’m afraid you will be domestic violence

You can also customize something better like the EmailSubject of your email

I’m going a little overboard with the template

let msgTitle = ["Sweet little baby! Monday is another full day."."Little Kangkang! After yesterday and the morning and three and a half days off."."We're halfway through the week! Be happy today too oh Je t'aime"."Thursday! No matter where you are, I will always be in your turning distance. ich liebe dich"."Ha ha ha, half a day is coming! σε αγαπώ se agapo."Your husband is there. Tell him he loves you! Hum"
]
let EmailSubject = msgTitle[new Date().getDay() - 1]
Copy the code

Single dog critical hit * 9999999

EmailHour, EmialMinminute you can choose your own time like 13:14, 5:20, etc. I won’t be here to join in the fun

Perform this operation

node main.js
Copy the code

The results of

Note the address

[0] github.com/nodemailer/…

[1] github.com/node-schedu…

[2] www.cnblogs.com/zhongweiv/p…