index.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. 'use strict';
  2. const EventEmitter = require('events');
  3. const shared = require('../shared');
  4. const mimeTypes = require('../mime-funcs/mime-types');
  5. const MailComposer = require('../mail-composer');
  6. const DKIM = require('../dkim');
  7. const httpProxyClient = require('../smtp-connection/http-proxy-client');
  8. const util = require('util');
  9. const urllib = require('url');
  10. const packageData = require('../../package.json');
  11. const MailMessage = require('./mail-message');
  12. const net = require('net');
  13. const dns = require('dns');
  14. const crypto = require('crypto');
  15. /**
  16. * Creates an object for exposing the Mail API
  17. *
  18. * @constructor
  19. * @param {Object} transporter Transport object instance to pass the mails to
  20. */
  21. class Mail extends EventEmitter {
  22. constructor(transporter, options, defaults) {
  23. super();
  24. this.options = options || {};
  25. this._defaults = defaults || {};
  26. this._defaultPlugins = {
  27. compile: [(...args) => this._convertDataImages(...args)],
  28. stream: []
  29. };
  30. this._userPlugins = {
  31. compile: [],
  32. stream: []
  33. };
  34. this.meta = new Map();
  35. this.dkim = this.options.dkim ? new DKIM(this.options.dkim) : false;
  36. this.transporter = transporter;
  37. this.transporter.mailer = this;
  38. this.logger = shared.getLogger(this.options, {
  39. component: this.options.component || 'mail'
  40. });
  41. this.logger.debug(
  42. {
  43. tnx: 'create'
  44. },
  45. 'Creating transport: %s',
  46. this.getVersionString()
  47. );
  48. // setup emit handlers for the transporter
  49. if (typeof transporter.on === 'function') {
  50. // deprecated log interface
  51. this.transporter.on('log', log => {
  52. this.logger.debug(
  53. {
  54. tnx: 'transport'
  55. },
  56. '%s: %s',
  57. log.type,
  58. log.message
  59. );
  60. });
  61. // transporter errors
  62. this.transporter.on('error', err => {
  63. this.logger.error(
  64. {
  65. err,
  66. tnx: 'transport'
  67. },
  68. 'Transport Error: %s',
  69. err.message
  70. );
  71. this.emit('error', err);
  72. });
  73. // indicates if the sender has became idle
  74. this.transporter.on('idle', (...args) => {
  75. this.emit('idle', ...args);
  76. });
  77. }
  78. /**
  79. * Optional methods passed to the underlying transport object
  80. */
  81. ['close', 'isIdle', 'verify'].forEach(method => {
  82. this[method] = (...args) => {
  83. if (typeof this.transporter[method] === 'function') {
  84. return this.transporter[method](...args);
  85. } else {
  86. this.logger.warn(
  87. {
  88. tnx: 'transport',
  89. methodName: method
  90. },
  91. 'Non existing method %s called for transport',
  92. method
  93. );
  94. return false;
  95. }
  96. };
  97. });
  98. // setup proxy handling
  99. if (this.options.proxy && typeof this.options.proxy === 'string') {
  100. this.setupProxy(this.options.proxy);
  101. }
  102. }
  103. use(step, plugin) {
  104. step = (step || '').toString();
  105. if (!this._userPlugins.hasOwnProperty(step)) {
  106. this._userPlugins[step] = [plugin];
  107. } else {
  108. this._userPlugins[step].push(plugin);
  109. }
  110. }
  111. /**
  112. * Sends an email using the preselected transport object
  113. *
  114. * @param {Object} data E-data description
  115. * @param {Function?} callback Callback to run once the sending succeeded or failed
  116. */
  117. sendMail(data, callback) {
  118. let promise;
  119. if (!callback && typeof Promise === 'function') {
  120. promise = new Promise((resolve, reject) => {
  121. callback = shared.callbackPromise(resolve, reject);
  122. });
  123. }
  124. if (typeof this.getSocket === 'function') {
  125. this.transporter.getSocket = this.getSocket;
  126. this.getSocket = false;
  127. }
  128. let mail = new MailMessage(this, data);
  129. this.logger.debug(
  130. {
  131. tnx: 'transport',
  132. name: this.transporter.name,
  133. version: this.transporter.version,
  134. action: 'send'
  135. },
  136. 'Sending mail using %s/%s',
  137. this.transporter.name,
  138. this.transporter.version
  139. );
  140. this._processPlugins('compile', mail, err => {
  141. if (err) {
  142. this.logger.error(
  143. {
  144. err,
  145. tnx: 'plugin',
  146. action: 'compile'
  147. },
  148. 'PluginCompile Error: %s',
  149. err.message
  150. );
  151. return callback(err);
  152. }
  153. mail.message = new MailComposer(mail.data).compile();
  154. mail.setMailerHeader();
  155. mail.setPriorityHeaders();
  156. mail.setListHeaders();
  157. this._processPlugins('stream', mail, err => {
  158. if (err) {
  159. this.logger.error(
  160. {
  161. err,
  162. tnx: 'plugin',
  163. action: 'stream'
  164. },
  165. 'PluginStream Error: %s',
  166. err.message
  167. );
  168. return callback(err);
  169. }
  170. if (mail.data.dkim || this.dkim) {
  171. mail.message.processFunc(input => {
  172. let dkim = mail.data.dkim ? new DKIM(mail.data.dkim) : this.dkim;
  173. this.logger.debug(
  174. {
  175. tnx: 'DKIM',
  176. messageId: mail.message.messageId(),
  177. dkimDomains: dkim.keys.map(key => key.keySelector + '.' + key.domainName).join(', ')
  178. },
  179. 'Signing outgoing message with %s keys',
  180. dkim.keys.length
  181. );
  182. return dkim.sign(input, mail.data._dkim);
  183. });
  184. }
  185. this.transporter.send(mail, (...args) => {
  186. if (args[0]) {
  187. this.logger.error(
  188. {
  189. err: args[0],
  190. tnx: 'transport',
  191. action: 'send'
  192. },
  193. 'Send Error: %s',
  194. args[0].message
  195. );
  196. }
  197. callback(...args);
  198. });
  199. });
  200. });
  201. return promise;
  202. }
  203. getVersionString() {
  204. return util.format('%s (%s; +%s; %s/%s)', packageData.name, packageData.version, packageData.homepage, this.transporter.name, this.transporter.version);
  205. }
  206. _processPlugins(step, mail, callback) {
  207. step = (step || '').toString();
  208. if (!this._userPlugins.hasOwnProperty(step)) {
  209. return callback();
  210. }
  211. let userPlugins = this._userPlugins[step] || [];
  212. let defaultPlugins = this._defaultPlugins[step] || [];
  213. if (userPlugins.length) {
  214. this.logger.debug(
  215. {
  216. tnx: 'transaction',
  217. pluginCount: userPlugins.length,
  218. step
  219. },
  220. 'Using %s plugins for %s',
  221. userPlugins.length,
  222. step
  223. );
  224. }
  225. if (userPlugins.length + defaultPlugins.length === 0) {
  226. return callback();
  227. }
  228. let pos = 0;
  229. let block = 'default';
  230. let processPlugins = () => {
  231. let curplugins = block === 'default' ? defaultPlugins : userPlugins;
  232. if (pos >= curplugins.length) {
  233. if (block === 'default' && userPlugins.length) {
  234. block = 'user';
  235. pos = 0;
  236. curplugins = userPlugins;
  237. } else {
  238. return callback();
  239. }
  240. }
  241. let plugin = curplugins[pos++];
  242. plugin(mail, err => {
  243. if (err) {
  244. return callback(err);
  245. }
  246. processPlugins();
  247. });
  248. };
  249. processPlugins();
  250. }
  251. /**
  252. * Sets up proxy handler for a Nodemailer object
  253. *
  254. * @param {String} proxyUrl Proxy configuration url
  255. */
  256. setupProxy(proxyUrl) {
  257. let proxy = urllib.parse(proxyUrl);
  258. // setup socket handler for the mailer object
  259. this.getSocket = (options, callback) => {
  260. let protocol = proxy.protocol.replace(/:$/, '').toLowerCase();
  261. if (this.meta.has('proxy_handler_' + protocol)) {
  262. return this.meta.get('proxy_handler_' + protocol)(proxy, options, callback);
  263. }
  264. switch (protocol) {
  265. // Connect using a HTTP CONNECT method
  266. case 'http':
  267. case 'https':
  268. httpProxyClient(proxy.href, options.port, options.host, (err, socket) => {
  269. if (err) {
  270. return callback(err);
  271. }
  272. return callback(null, {
  273. connection: socket
  274. });
  275. });
  276. return;
  277. case 'socks':
  278. case 'socks5':
  279. case 'socks4':
  280. case 'socks4a': {
  281. if (!this.meta.has('proxy_socks_module')) {
  282. return callback(new Error('Socks module not loaded'));
  283. }
  284. let connect = ipaddress => {
  285. this.meta.get('proxy_socks_module').createConnection({
  286. proxy: {
  287. ipaddress,
  288. port: proxy.port,
  289. type: Number(proxy.protocol.replace(/\D/g, '')) || 5
  290. },
  291. target: {
  292. host: options.host,
  293. port: options.port
  294. },
  295. command: 'connect',
  296. authentication: !proxy.auth
  297. ? false
  298. : {
  299. username: decodeURIComponent(proxy.auth.split(':').shift()),
  300. password: decodeURIComponent(proxy.auth.split(':').pop())
  301. }
  302. }, (err, socket) => {
  303. if (err) {
  304. return callback(err);
  305. }
  306. return callback(null, {
  307. connection: socket
  308. });
  309. });
  310. };
  311. if (net.isIP(proxy.hostname)) {
  312. return connect(proxy.hostname);
  313. }
  314. return dns.resolve(proxy.hostname, (err, address) => {
  315. if (err) {
  316. return callback(err);
  317. }
  318. connect(address);
  319. });
  320. }
  321. }
  322. callback(new Error('Unknown proxy configuration'));
  323. };
  324. }
  325. _convertDataImages(mail, callback) {
  326. if ((!this.options.attachDataUrls && !mail.data.attachDataUrls) || !mail.data.html) {
  327. return callback();
  328. }
  329. mail.resolveContent(mail.data, 'html', (err, html) => {
  330. if (err) {
  331. return callback(err);
  332. }
  333. let cidCounter = 0;
  334. html = (html || '').toString().replace(/(<img\b[^>]* src\s*=[\s"']*)(data:([^;]+);[^"'>\s]+)/gi, (match, prefix, dataUri, mimeType) => {
  335. let cid = crypto.randomBytes(10).toString('hex') + '@localhost';
  336. if (!mail.data.attachments) {
  337. mail.data.attachments = [];
  338. }
  339. if (!Array.isArray(mail.data.attachments)) {
  340. mail.data.attachments = [].concat(mail.data.attachments || []);
  341. }
  342. mail.data.attachments.push({
  343. path: dataUri,
  344. cid,
  345. filename: 'image-' + ++cidCounter + '.' + mimeTypes.detectExtension(mimeType)
  346. });
  347. return prefix + 'cid:' + cid;
  348. });
  349. mail.data.html = html;
  350. callback();
  351. });
  352. }
  353. set(key, value) {
  354. return this.meta.set(key, value);
  355. }
  356. get(key) {
  357. return this.meta.get(key);
  358. }
  359. }
  360. module.exports = Mail;