/
server.js
79 lines (65 loc) · 1.88 KB
/
server.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
var puts = require('sys').puts,
express = require('express'),
nodemailer = require('nodemailer'),
url = require('url'),
http = require('http');
function downloadImage(imageUrl, callback) {
var client = http.createClient(80, url.parse(imageUrl).hostname);
var request = client.request('GET', imageUrl, {"host": url.parse(imageUrl).hostname});
request.end();
request.addListener('response', function (response) {
response.setEncoding('binary')
var body = '';
response.addListener('data', function (chunk) {
body += chunk;
});
response.addListener("end", function() {
callback(body);
});
});
}
nodemailer.SMTP = {
host: 'smtp.gmail.com', // required
use_authentication: true, // optional, false by default
user: process.env.GMAIL_ACCOUNT, // used only when use_authentication is true
pass: process.env.GMAIL_PASSWORD // used only when use_authentication is true*/
};
function sendMail(imageData, filename, email, callback) {
var attachmentList = [{
filename: filename,
contents: new Buffer(imageData, 'binary')
}];
var mailData = {
sender: process.env.GMAIL_ACCOUNT,
to: email,
subject: "Here is an image for you: " + filename,
body: "Here's that image you asked for.",
attachments: attachmentList
}
nodemailer.send_mail(mailData, function(err, success) {
callback(err, success);
});
}
var app = express.createServer();
app.get('/', function(req, res){
var imageUrl = req.param('imageUrl'),
filename = ( imageUrl.match(/^.*\/([^/]*)$/)[1] ).match(/([^?&]*)/)[1];
downloadImage(imageUrl, function(imageData) {
sendMail(imageData, filename, req.param('email'), function(err, success) {
res.contentType('application/json');
if (err) {
res.send({
success: false
});
} else {
res.send({
success: true
});
}
});
});
});
app.on('error', function(err) {
puts(err);
});
app.listen(80);