I am building a simple server with Koa and Node 0.11. I want an email to be sent to me when a user submits an inquiry from my site. Of course, I want to alert the users if the email fails to send for whatever reason, but I'm not sure of the best way to "wait" for that to happen.
My relevant server code is pretty simple:
app.put('/inquiry', function *() {
var status = yield sendEmail('test', "my message", "me@mysite" );
this.body = status;
});
function sendEmail(subject, message, to) {
var fromEmail = 'you@yoursite.com';
var tags = ['subject'];
var to = {email: to};
return function() {
mandrill('/messages/send',
{
message: {
"from_email":fromEmail,
"to":[to],
"text":message,
"tags":tags
}
},
function (error, response) {
if (error) {
console.log(JSON.stringify(error));
return error;
}
else {
console.log("Mandrill result: "+response);
return response;
}
};
);
};
};
The problem that I'm having is that the Mandrill.send() function doesn't return anything, and I'm not sure what the best thing to do is.
You just need to wrap it up in an anonymous function like this:
function sendEmail(subject, message) {
var fromEmail = 'test@elliottregan.com';
var tags = ['subject'];
var to = {email:'oatmealsnap@gmail.com'};
return function(callback) {
mandrill('/messages/send', {
message: {
"from_email":fromEmail,
"to":[to],
"text":message,
"tags":tags
}
},
function (error, response) {
if (error) {
console.log(JSON.stringify(error));
return error;
}
else {
console.log("Mandrill result: "+response);
callback(null, response);
}
}
)}
};