Created
August 3, 2011 16:16
-
-
Save dscape/1123036 to your computer and use it in GitHub Desktop.
Make the postmark api look like node_mailer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var request = require('request') | |
, _ = require('underscore'); | |
function send_mail(message, callback) { | |
if(typeof exports.SMTP.api_key !== "string") { | |
console.log(exports.SMTP) | |
callback(new Error("No API Key was given")); | |
return; | |
} | |
if(typeof exports.SMTP !== "object") { | |
callback(new Error("Invalid SMTP options")); | |
return; | |
} | |
var tr_message = {} | |
, postmark_headers = | |
{ "Accept": "application/json" | |
, "Content-Type": "application/json" | |
, "X-Postmark-Server-Token": exports.SMTP.api_key | |
}; | |
if(message.sender) { | |
tr_message.From = message.sender; | |
} | |
if(message.to) { | |
tr_message.To = message.to; | |
} | |
if(message.cc) { | |
tr_message.Cc = message.cc; | |
} | |
if(message.bcc) { | |
tr_message.Bcc = message.bcc; | |
} | |
if(message.subject) { | |
tr_message.Subject = message.subject; | |
} | |
if(message.reply_to) { | |
tr_message.ReplyTo = message.reply_to; | |
} | |
if(message.body) { | |
tr_message.TextBody = message.body; | |
} | |
if(message.html) { | |
tr_message.HtmlBody = message.html; | |
} | |
if(message.headers) { | |
tr_message.Headers = message.headers; | |
} | |
if(message.attachments) { | |
tr_message.Attachments = _.map( | |
message.attachments, | |
function (attachment) { | |
return { Name: attachment.filename | |
, Content: attachment.contents | |
}; | |
} | |
); | |
} | |
var post = | |
{ uri: ("http" + (exports.SMTP.ssl ? "s" : "") + "://" + exports.SMTP.host + | |
":" + (exports.SMTP.ssl ? 443 : 80) + "/email") | |
, method: "POST" | |
, headers: postmark_headers | |
, body: JSON.stringify(tr_message) | |
}; | |
console.log(exports.SMTP) | |
request(post, | |
function (e,h,b) { | |
if(e) { | |
callback(e); | |
return; | |
} | |
var body = JSON.parse(b); | |
if (h.statusCode == 200) { | |
callback(null,body); | |
} | |
else if (h.statusCode == 401) { | |
callback(new Error(body.Message)); | |
} | |
else if (h.statusCode == 422) { | |
callback(new Error(body.Message)); | |
} | |
else { | |
callback(new Error(body.Message)); | |
} | |
return; | |
} | |
); | |
} | |
module.exports = exports; | |
exports.send_mail = send_mail; | |
exports.version = "0.0.1"; | |
exports.path = __dirname; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment