Nodejs獲取桌面截圖戴质,并定時發(fā)送給指定郵箱
代碼地址: https://github.com/klren0312/NodejsGetScreenshotSend
前面還寫過Python獲取截圖并發(fā)郵件的
代碼地址:https://github.com/klren0312/PythonGetScreenshotSend
1.安裝相關(guān)包
npm install --save screenshot-desktop //截圖
npm install --save nodemailer //發(fā)郵件
npm install --save node-schedule //定時
2.screenshot-desktop
截圖的包
網(wǎng)址: https://github.com/bencevans/screenshot-desktop
3.nodemailer
發(fā)郵件用的包
網(wǎng)址: https://nodemailer.com/about/
4.node-schedule
定時使用的包
網(wǎng)址: https://github.com/node-schedule/node-schedule
5.引入包
const screenshot = require('screenshot-desktop')
const nodemailer = require('nodemailer')
const schedule = require('node-schedule')
const fs = require('fs')//nodejs 文件操作的包
6.配置發(fā)送郵件的郵箱
var transporter = nodemailer.createTransport({
host:"smtp服務(wù)器地址",
secure:true,
port:端口, //端口注意了 分兩種纷闺,一種是有ssl的一種是沒有ssl
auth: {
user: "發(fā)送的郵箱",
pass: "密碼"
},
debug: true // include SMTP traffic in the logs
});
7.設(shè)置定時
設(shè)置每一分鐘發(fā)送一次
var rule = new schedule.RecurrenceRule();
rule.second = 10;
var j = schedule.scheduleJob(rule,function(){
})
8.設(shè)置截圖
screenshot()
.then((img) => {
//將截取的圖片存入根目錄out.jpg
fs.writeFile('out.jpg', img,function(err){
if(err){
throw err
}
console.log('written to out.jpg')
});
})
9.設(shè)置發(fā)送的郵件內(nèi)容
看了官方的example才知道刨仑,圖片要寫到下面的attachments中滴某,并提供cid姑原,給上面html中的img調(diào)用凭戴。
var message = {
from:"發(fā)送郵件地址",
to:"接受郵件地址",
subject:"桌面截圖",
html:'桌面截圖:![](cid:test)',
//附加文件佩抹,提供cid給上面的img調(diào)用
attachments:[
{
filename: 'out',
path: __dirname + '/out.jpg',
cid: 'test' // should be as unique as possible
}
]
}
10.發(fā)送郵件
transporter.sendMail(message, (error, info) => {
if (error) {
console.log('Error occurred');
console.log(error.message);
return;
}
console.log('Message sent successfully!');
console.log('Server responded with "%s"', info.response);
transporter.close();
});