-
Notifications
You must be signed in to change notification settings - Fork 0
/
email.js
executable file
·129 lines (109 loc) · 2.6 KB
/
email.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#!/usr/local/bin/node
var mail = require('mail'),
spawn = require('child_process').spawn,
fs = require('fs'),
config,
message,
weather = '',
now = new Date();
function loadConfig(cb) {
if(process.argv.length < 3) {
console.log('Must specify config.json file');
process.exit(1);
}
fs.readFile(process.argv[2], 'utf8', function(err, data) {
if(err) {
console.log('error reading config file '+ err);
process.exit(1);
}
config = JSON.parse(data);
cb();
});
}
function loadWeatherFile(cb) {
var hourly,
params = [
'--disk-cache=yes',
'--load-images=no',
'--load-plugins=no',
'hourly.js',
config.accuweatherUrl
],
onExit = function(code) {
if(code === 0) {
cb();
} else {
console.log('child process did not exit normally '+code);
process.exit(1);
}
},
onStdout = function(data) {
var json = data.toString('utf8');
weather = JSON.parse(json);
weather.day = new Date(weather.day);
};
hourly = spawn(config.phantomjs, params, {});
hourly.stdout.on('data', onStdout);
hourly.on('exit', onExit);
}
function generateSubject() {
return 'Hourly forecast for ' + weather.day.toDateString();
}
function generateBody() {
var out = [],
idx,
results = weather.results,
length = results.length,
errors = weather.errors;
for(idx = 0; idx < length; idx++) {
out.push(results[idx].time);
out.push(' ');
out.push(results[idx].conditions);
out.push(' temp ');
out.push(results[idx].temp);
out.push(' realfeel ');
out.push(results[idx].realfeel);
out.push('\n');
}
//Check for parsing errors
length = errors.length;
if(length > 0) {
out.push('\n\nErrors: \n');
for(idx = 0; idx < length; idx++) {
out.push(errors[idx]);
out.push('\n');
}
}
return out.join('');
}
function sendEmail() {
var body, subject;
loadWeatherFile(function() {
subject = generateSubject();
body = generateBody();
mail.message({
from:config.from,
to: config.to.join(','),
subject: subject
}).body(body).send(function(err) {
if(err) {
console.log('error sending');
console.log(err);
process.exit(1);
} else {
process.exit(0);
}
});
});
}
(function() {
var body, subject;
loadConfig(function() {
mail = mail.Mail({
host: config.host,
username: config.username,
password: config.password
});
sendEmail();
});
}());