UNPKG

2.41 kBJavaScriptView Raw
1var request;
2try {
3 request = require("request"); // use NPM installed if available.
4} catch(e) { // resort to vendored.
5 request = require("./vendor/request");
6}
7var sys = require("sys")
8
9module.exports = (function (api_key, options) {
10 if (typeof api_key == undefined) {
11 throw("You must provide your postmark API key");
12 }
13 if (typeof options === 'undefined') { options = {}; }
14 if (options.ssl && options.ssl !== true) { options.ssl = false; }
15
16
17
18 return {
19 send: function(message, callback) {
20
21 var valid_parameters = ["From", "To", "Cc", "Bcc", "Subject", "Tag", "HtmlBody", "TextBody", "ReplyTo", "Headers", "Attachments"]
22 var valid_attachment_parameters = ["Name", "Content", "ContentType"];
23 var attr, attach;
24 for (attr in message) {
25 if (valid_parameters.indexOf(attr) < 0) {
26 throw("You can only provide attributes that work with the Postmark JSON message format. Details: http://developer.postmarkapp.com/developer-build.html#message-format");
27 }
28 if (attr == "Attachments") {
29 for(attach in message[attr]) {
30 var attach_attr;
31 for (attach_attr in message[attr][attach]) {
32 if (valid_attachment_parameters.indexOf(attach_attr) < 0) {
33 throw("You can only provide attributes for attachments that work with the Postmark JSON message format. Details: http://developer.postmarkapp.com/developer-build.html#attachments");
34 }
35 }
36 }
37 }
38 }
39
40 var postmark_uri = "http://api.postmarkapp.com/email"
41 if (options.ssl) {
42 postmark_uri = "https://api.postmarkapp.com/email";
43 }
44
45 postmark_headers = {
46 "Accept": "application/json",
47 "Content-Type": "application/json",
48 "X-Postmark-Server-Token": api_key
49 }
50 request({uri: postmark_uri, method: "POST", body: JSON.stringify(message), headers: postmark_headers}, function (error, response, body) {
51 if (response.statusCode == 401) {
52 throw("Incorrect Postmark API Key header")
53 } else if (response.statusCode == 422) {
54 throw("Incorrect or Malformed JSON message: "+JSON.parse(body["Message"]))
55 } else if (response.statusCode == 200) {
56 return true;
57 } else {
58 throw("Something wrong with Postmark");
59 }
60 });
61 }
62 }
63});
\No newline at end of file