当前位置: 首页 > 后端技术 > Node.js

【谁说程序员不浪漫】用node每天给女朋友发送浪漫邮件

时间:2023-04-03 15:36:21 Node.js

先看看效果吧。内容包括现在的时间,和女朋友的纪念日,当天的天气,当天的一句话和生活小窍门(爱从小事做起)Packagesused"cheerio":"^1.0.0-rc.3",//抓取网站内容"node-schedule":"^1.3.2",//定时器"nodemailer":"^6.3.1",//发送邮件"nodemailer-smtp-transport":"^2.7.4","superagent":"^5.1.0"目录结构整体思路主要分为三步:1.爬取数据,通过API获取数据2.处理数据,整合成模板发送3.设置发送时间并发送邮件1.获取数据本案例的数据来源有两个,其中“一天一句话”是通过爬取ONE网页版到网站(网址:http://wufazhuce.com/)获取的天气信息和健康提示是通过天行API获取的(URL:https://www.tianapi.com/signup.html?source=474284281),使用前需要申请apikey。config/confi.js为配置信息module.exports={MEMORIAL_DAY:'2016-09-17',//女友纪念日TXAPIKEY:'',//这里必须填写个人申请的天行apikey,请替换成自己的//邮箱配置(qq邮箱)emailUser:"@qq.com",//account,你自定义的域名邮箱账号emailPass:"",//password,自己打开SMPT得到的密码toEmailList:['2657179843@qq.com'],//收件人列表,可同时发送给多人emailSubject:'馒头耙的每日关注',//邮件标题}这里需要说明一下,上面的emailPass不是指你的邮箱登录密码,是你的邮箱开通SMTP服务的密码。这里我们以QQ邮箱为例。登录QQ邮箱,点击设置->账号,向下滚动找到SMTP服务。点击打开后,会弹出你的服务密码。config/superagent.js爬取页面信息constsuperagent=require('superagent')//requestfunctionreq(url,method,params,data,cookies){returnnewPromise(function(resolve,reject){superagent(method,url).query(params).send(data).set('Content-Type','application/x-www-form-urlencoded').end(function(err,response){if(err){reject(err)}resolve(response)})})}module.exports={req}utils/cheerio在.js中获取数据,内容如下:constcheerio=require('cheerio');constsuperagent=require('../config/superagent');constONE='http://wufazhuce.com/';//ONE的网页版网站constTXHOST='http://api.tianapi.com/txapi/';//天行hostconstconfig=require('../config/config')asyncfunctiongetOne(){//获取当天的一句话try{letres=awaitsuperagent.req(ONE,'GET');让$=cheerio.load(res.text);让todayOneList=$('#carousel-one.carousel-inner.item');让todayOne=$(todayOneList[0]).find('.fp-one-cita').text().replace(/(^\s*)|(\s*$)/g,'');今天返回一个;}catch(err){console.log('Error',err);返回错误;}}asyncfunctiongetTXweather(){//获取天星天气leturl=TXHOST+'tianqi/';try{letres=awaitsuperagent.req(url,'GET',{key:config.TXAPIKEY,city:'重庆'});让content=JSON.parse(res.text);if(content.code===200){让todayInfo=content.newslist[0];返回今天的信息;}else{console.log('获取接口失败',content.code);}}catch(err){console.log('获取接口失败',err);}}asyncfunctiongetTXhealthtip(){//获取健康提示leturl=TXHOST+'healthtip/';尝试{letres=awaitsuperagent.req(url,'GET',{key:config.TXAPIKEY,});让内容=JSON.parse(res.文本);如果(content.code===200){让healthtip=content.newslist[0].content;返回健康提示;}else{console.log('获取接口失败',content.code);}}catch(err){console.log('获取接口失败',err);}}module.exports={getOne,getTXweather,getTXhealthtip}二、处理数据处理时间:utils/dateTime.js(获取当天时间,计算当天与女友周年纪念日的差值,格式化时间)functiongetDay(日期){vardate2=newDate();vardate1=新日期(日期);variDays=parseInt(Math.abs(date2.getTime()-date1.getTime())/1000/60/60/24);returniDays;}functiongetToday(){让今天=newDate()varyear=today.getFullYear();varmonth=today.getMonth()+1;varday=today.getDate();return`今天是${year}${month}${day}`}functionformatDate(date){vartempDate=newDate(date);varyear=tempDate.getFullYear();varmonth=tempDate.getMonth()+1;varday=tempDate.getDate();varhour=tempDate.getHours();瓦米n=tempDate.getMinutes();varsecond=tempDate.getSeconds();varweek=tempDate.getDay();变量str='';if(week===0){str='周日';}elseif(week===1){str='星期一';}elseif(week===2){str='星期二';}elseif(week===3){str='星期三';}elseif(week===4){str='星期四';}elseif(week===5){str='星期五';}elseif(week===6){str='星期六';}如果(小时<10){小时='0'+小时;}if(min<10){min='0'+min;}if(second<10){second='0'+second;}returnyear+'-'+month+'-'+day+'day'+hour+':'+min+''+str;}module.exports={getDay,formatDate,getToday};处理发送邮件信息:utils/email.js//导入邮件模块varnodemailer=require('nodemailer');varsmtpTransport=require('nodemailer-smtp-transport');constconfig=require('../config/config')//开启一个SMTP连接池vartransport=nodemailer.createTransport(smtpTransport({host:"smtp.qq.com",//qq邮箱主机secure:true,//使用SSLsecureConnection:true,//使用SSLport:465,//SMTPportauth:{user:config.emailUser,//accountyourcustomdomainemailaccountpass:config.emailPass//密码是自己打开SMPT得到的密码}}));functionsendEmail(htmlcon){//设置邮件内容用html拼接,美化发送内容varmailOptions={from:config.emailUser,//发送地址:config.toEmailList,//列表主题:config.emailSubject,//标题文本:“文本”,html:htmlcon//html内容}transport.sendMail(mailOptions,function(error,response){if(error){console.log("fail:"+error);console.log("发送失败");}else{console.log("发送成功");}transport.close();//如果没有有用,关闭连接池});}module.exports={sendEmail}3.设置发送时间和发送邮件设置发送时间:utils/schedule.jsconstschedule=require('node-schedule')//dateparameter//其他规则见https://www.npmjs.com/package/node-schedule//规则参数解释*代表通配符////******//┬┬┬┬┬//│││││|//││││└星期几(0-7)(0或7是星期日)//││││└──────月(1-12)//│││└────────────月中的第几天(1-31)//││└────────────────小时(0-23)//│└──────────────────────分钟(0-59)//└────────────────────────────second(0-59,OPTIONAL)//每分钟第30秒触发:'30*****'////每小时第1分30秒触发:'301****'////每天早上1:1:30触发:'3011***'////每月第一天1:1:30触发:'30111**'////每周1:1:30触发:'3011**1'functionsetSchedule(date,callback){schedule.scheduleJob(date,callback)}module.exports={setSchedule}index.js入口文件constEmail=require('./utils/email')constSchedule=require('./utils/schedule')constDateTime=require('./utils/dateTime')constCheerio=require('./utils/cheerio')constconfig=require('./config/config')asyncfunctionrun(){letoneText=awaitCheerio.getOne()letweather=awaitCheerio.getTXweather()lethealthtip=awaitCheerio.getTXhealthtip()让今天=DateTime.getToday()Email.sendEmail(`

${today}${weather.week}

初恋馒头的${DateTime.getDay(config.MEMORIAL_DAY)}day

${weather.lowest}~${weather.highest}${weather.weather}${weather.wind}${weather.windspeed}

${weather.tips}

${oneText}

生活小贴士:${healthtip}
`)}时间表。放schedule("017****",function(){run()})最后执行nodeindex.js,女友会在指定时间收到你的日常关系。当然,如果你要发送需要部署在云服务器上,就不用担心了。点自动发送后我会在项目中加入更多的功能(可以在网站上随时修改发件人、收件人、发送时间等信息,可以自定义发送内容等功能),有兴趣的朋友可以源码点击:https://github.com/DengZhanyong/emailBot(如果觉得还不错,给我一个star,您的支持是我进步的动力)我的个人博客网址:www.dzyong.com