初始化
npm init
安装所需要的包
npm install art-template cheerio nodemailer
index.js
const http=require("http");
const cheerio=require("cheerio"); //
const template = require('art-template'); //模板
const nodemailer = require('nodemailer'); //发送邮箱
//获取时间
function getDays() {
return new Promise((resolve,reject)=>{
const day=new Date("2019-08-01");
const now=new Date();
const today=now.getFullYear()+"-"+(now.getMonth()+1)+"-"+now.getDate() //获取当前时间
const countDay=Math.floor((now-day)/1000/60/60/24); //计算时间
const dayObject={
countDay,
today
}
resolve(dayObject)
})
}
//爬取one网站 http://wufazhuce.com/
async function getOne(){
const {countDay,today}=await getDays();return new Promise((resolve,reject)=>{
http.get("http://wufazhuce.com/",res=>{
let data;
res.on("data",d=>{
data+=d;
})
res.on("end",d=>{
let $=cheerio.load(data);
const imgUrl=$(".fp-one-imagen").attr("src");
const tips=$(".fp-one-cita").eq(0).text();
const html=template(__dirname + '/index.html',{countDay,today,imgUrl,tips})
resolve(html)
})
})
})
}
async function main() {
const html=await getOne();
let transporter = nodemailer.createTransport({
host: 'smtp.163.com',
port: 465,
secure: true, // true for 465, false for other ports
auth: {
user: "", //我的邮箱 (写你的邮箱)
pass: "" // 授权码 (你的邮箱授权码)
}
});
let info = await transporter.sendMail({
from: '', // 发件箱 (写你的邮箱)
to: '', // 收件箱
subject: '我与NodeJs', // 主题
/* text: 'Hello world?', // plain text body*/
html: html // 发送的页面
});
}
main();
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div class="wrapper" style="margin: 0 auto;display: flex;flex-direction: column;align-items: center;">
<div class="time" style="display: flex;margin-bottom: 10px;justify-content: space-around;">
<div style="font-size: 18px;color:#aaa;margin: 0 10px;">今天是我学习NodeJS的第{{countDay}}天</div>
<div style="font-size: 18px;color:#aaa; margin: 0 10px;">{{today}}</div>
</div>
<div class="one" style="text-align: center;">
<img src="{{imgUrl}}" style="border-radius: 5px;border: 1px solid #ddd;padding: 5px;display: block;">
<p style="border-bottom: 4px solid #ddd;padding-bottom: 10px;display: inline-block;">{{tips}}</p>
</div>
</div>
</body>
</html>
