Ghost/core/server/mail.js

102 lines
2.9 KiB
JavaScript
Raw Normal View History

var cp = require('child_process'),
2014-02-05 12:40:30 +04:00
_ = require('lodash'),
Promise = require('bluebird'),
nodemailer = require('nodemailer'),
config = require('./config');
2013-08-21 00:19:47 +04:00
function GhostMailer(opts) {
opts = opts || {};
this.transport = opts.transport || null;
}
// ## E-mail transport setup
// *This promise should always resolve to avoid halting Ghost::init*.
GhostMailer.prototype.init = function () {
var self = this;
self.state = {};
if (config.mail && config.mail.transport) {
this.createTransport();
return Promise.resolve();
2013-08-21 00:19:47 +04:00
}
// Attempt to detect and fallback to `sendmail`
return this.detectSendmail().then(function (binpath) {
self.transport = nodemailer.createTransport('sendmail', {
path: binpath
});
self.state.usingSendmail = true;
}).catch(function () {
self.state.emailDisabled = true;
self.transport = null;
2013-08-21 00:19:47 +04:00
});
};
GhostMailer.prototype.isWindows = function () {
return process.platform === 'win32';
};
GhostMailer.prototype.detectSendmail = function () {
if (this.isWindows()) {
return Promise.reject();
2013-08-21 00:19:47 +04:00
}
return new Promise(function (resolve, reject) {
2013-08-21 00:19:47 +04:00
cp.exec('which sendmail', function (err, stdout) {
if (err && !/bin\/sendmail/.test(stdout)) {
return reject();
}
resolve(stdout.toString().replace(/(\n|\r|\r\n)$/, ''));
2013-08-21 00:19:47 +04:00
});
});
};
GhostMailer.prototype.createTransport = function () {
this.transport = nodemailer.createTransport(config.mail.transport, _.clone(config.mail.options) || {});
2013-08-21 00:19:47 +04:00
};
GhostMailer.prototype.fromAddress = function () {
var from = config.mail && config.mail.fromaddress,
domain;
if (!from) {
// Extract the domain name from url set in config.js
domain = config.url.match(new RegExp('^https?://([^/:?#]+)(?:[/:?#]|$)', 'i'));
domain = domain && domain[1];
// Default to ghost@[blog.url]
from = 'ghost@' + domain;
}
return from;
};
2013-08-21 00:19:47 +04:00
// Sends an e-mail message enforcing `to` (blog owner) and `from` fields
// This assumes that api.settings.read('email') was aready done on the API level
GhostMailer.prototype.send = function (message) {
var self = this,
to,
sendMail;
message = message || {};
to = message.to || false;
2013-08-21 00:19:47 +04:00
if (!this.transport) {
return Promise.reject(new Error('Email Error: No e-mail transport configured.'));
2013-08-21 00:19:47 +04:00
}
if (!(message && message.subject && message.html && message.to)) {
return Promise.reject(new Error('Email Error: Incomplete message data.'));
2013-08-21 00:19:47 +04:00
}
sendMail = Promise.promisify(self.transport.sendMail.bind(self.transport));
message = _.extend(message, {
from: self.fromAddress(),
to: to,
generateTextFromHTML: true
2013-08-21 00:19:47 +04:00
});
return sendMail(message);
2013-08-21 00:19:47 +04:00
};
module.exports = new GhostMailer();