未加星标

Node.js: Sending Email Notifications Using Nodemailer and Gmail

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二04 | 时间 2016 | 作者 红领巾 ] 0人收藏点击收藏

Node.js: Sending Email Notifications Using Nodemailer and Gmail

We all want to be in the loop and notified when certain events occur within our Node.js programs. For example, email notifications can be very important for creating situational awareness with IoT systems we develop that interact with our physical world. Email communication can be used to deliver messages to our inboxes as well as to deliver text messages in order to enable us to take more immediate action.

In today’s tutorial, we’ll walk through the steps of using the amazing Nodemailer package which has become the de facto standard for sending email messages in the Node.js world. Let’s get started so we can start seeing our own custom messages flow to our inbox!

Is the International Space Station NearMe?

Let’s continue our theme from the previous tutorial to utilize the ISS (International Space Station) as a “sensor” in the sky. As we read this “sensor”, we want to send a notification by email if the ISS is approaching our current location so we can walk outside and see it pass over us.

We’ll leverage a different API call this time around that enables us to supply our current coordinates and retrieve information on the next five times the ISS will pass over us. The following URL, for example, returns the next passes of the ISS based on San Diego coordinates: http://api.open-notify.org/iss-pass.json?lat=32.715738&lon=-117.161084

This URL returns the following JSON object:

{
"message": "success",
"request": {
"altitude": 100,
"datetime": 1476107333,
"latitude": 32.715738,
"longitude": -117.161084,
"passes": 5
},
"response": [
{
"duration": 506,
"risetime": 1476131595
},
{
"duration": 631,
"risetime": 1476137299
},
{
"duration": 469,
"risetime": 1476143206
},
{
"duration": 209,
"risetime": 1476149222
},
{
"duration": 362,
"risetime": 1476155044
}
]
}

Using this API, we can write the following code to invoke a URL every two minutes and retrieve the next times the ISS will pass over us. We could probably back down the loop frequency, but we’ll keep it at two minutes to ensure we catch any changes to the ISS trajectory that may occur.

const got = require('got');
const moment = require('moment');
const loopSeconds = 120;
const myLoc = { latitude: 32.715738, longitude: -117.161084 };
const url = `http://api.open-notify.org/iss-pass.json?lat=${myLoc.latitude}&lon=${myLoc.longitude}`;
function loop() {
got(url, { json: true })
.then(iss => {const nextPasses = iss.body.response;const now = moment();console.log('Next ISS passes near me');for (const pass of nextPasses) { const passTime = moment.unix(pass.risetime); const timeFromNow = moment.duration(passTime.diff(now)); const minutesFromNow = Number(timeFromNow.asMinutes()).toFixed(1); console.log(`${passTime} (in ${minutesFromNow} minutes) for ${pass.duration} seconds`);}
})
.catch(error => {console.log(error.response.body);
});
setTimeout(loop, loopSeconds * 1000);
}
loop();

To get this working, we will need to npm install both got to help us retrieve data from the web and moment to help us manipulate dates and times. We can install both of these at the same time using the following command:

$ npm install got moment

In our code, we utilize the incredible moment package to help us manipulate dates and times. This package should be part of the core Node.js built-in libraries, in my opinion, as it fills in the gap for the dearth of functionality that ships as part of the standard javascript date functions.

The risetime returned from the API returns a Unix timestamp which represents the number of seconds that have elapsed since the Unix Epoch which is 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970. We will run out of seconds in the year 2038 , but I digress. We use the moment.unix function to convert the Unix timestamp to a standard Moment timestamp that we are able manipulate in order to determine when the ISS will pass over us next.

Tell Me When the ISS Is within 30 Minutes of Passing over Me

Let’s modify our code so we can be notified when it is within 30 minutes of passing over us:

const got = require('got');
const moment = require('moment');
const loopSeconds = 120;
const myLoc = { latitude: 32.715738, longitude: -117.161084 };
const url = `http://api.open-notify.org/iss-pass.json?lat=${myLoc.latitude}&lon=${myLoc.longitude}`;
const warningMinutes = 30;
let providedNotification = false;
function sendNotification(message) {
console.log(`Could send email here: ${message}`);
}
function loop() {
got(url, { json: true })
.then(iss => {const nextPasses = iss.body.response;const now = moment();const pass = nextPasses[0];const passTime = moment.unix(pass.risetime);const timeFromNow = moment.duration(passTime.diff(now));const minutesFromNow = Number(timeFromNow.asMinutes()).toFixed(1);console.log(`${passTime} (in ${minutesFromNow} minutes) for ${pass.duration} seconds`);if (minutesFromNow <= warningMinutes) { if (!providedNotification) { sendNotification(`The ISS will pass over in ${minutesFromNow} minutes`); providedNotification = true; } } else { providedNotification = false; } }) .catch(error => {console.log(error.response.body);
});
setTimeout(loop, loopSeconds * 1000);
}
loop();

In this new iteration, we only analyze the next time the ISS will pass over us. We also send a notification if it is within 30 minutes of passing over us. You will also see that we have now created a sendNotification function as a placeholder that we will ultimately use to send email messages. If we have already invoked the sendNotication function, we don’t invoke it again. We only want to be notified once rather than bombarding our inbox with email messages every two minutes!

I Want to Send Email Using Node.js Nodemailer is Your Ticket!

Now that we have the foundational code in place, we are ready to start sending email with the help of Nodemailer !

For this exercise, we will be using Gmail. Sending email by Gmail with Nodemailer is not the most secure option in the world since your password is sent in plaintext so it can be intercepted using network sniffers. For this reason, I recommend that you create a test Gmail account for this exercise. There are other email options that we can use in production applications such as Mailgun ; however, they require a lot more ceremony to set up, and Gmail works great as a testing platform to understand the mechanics of sending email messages with Nodemailer.

After creating a te

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

主题: Node.jsJavaScriptJavaUTUTC
分页:12
转载请注明
本文标题:Node.js: Sending Email Notifications Using Nodemailer and Gmail
本站链接:http://www.codesec.net/view/481270.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(28)