index.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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 this.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. return this;
  111. }
  112. /**
  113. * Sends an email using the preselected transport object
  114. *
  115. * @param {Object} data E-data description
  116. * @param {Function?} callback Callback to run once the sending succeeded or failed
  117. */
  118. sendMail(data, callback) {
  119. let promise;
  120. if (!callback) {
  121. promise = new Promise((resolve, reject) => {
  122. callback = shared.callbackPromise(resolve, reject);
  123. });
  124. }
  125. if (typeof this.getSocket === 'function') {
  126. this.transporter.getSocket = this.getSocket;
  127. this.getSocket = false;
  128. }
  129. let mail = new MailMessage(this, data);
  130. this.logger.debug(
  131. {
  132. tnx: 'transport',
  133. name: this.transporter.name,
  134. version: this.transporter.version,
  135. action: 'send'
  136. },
  137. 'Sending mail using %s/%s',
  138. this.transporter.name,
  139. this.transporter.version
  140. );
  141. this._processPlugins('compile', mail, err => {
  142. if (err) {
  143. this.logger.error(
  144. {
  145. err,
  146. tnx: 'plugin',
  147. action: 'compile'
  148. },
  149. 'PluginCompile Error: %s',
  150. err.message
  151. );
  152. return callback(err);
  153. }
  154. mail.message = new MailComposer(mail.data).compile();
  155. mail.setMailerHeader();
  156. mail.setPriorityHeaders();
  157. mail.setListHeaders();
  158. this._processPlugins('stream', mail, err => {
  159. if (err) {
  160. this.logger.error(
  161. {
  162. err,
  163. tnx: 'plugin',
  164. action: 'stream'
  165. },
  166. 'PluginStream Error: %s',
  167. err.message
  168. );
  169. return callback(err);
  170. }
  171. if (mail.data.dkim || this.dkim) {
  172. mail.message.processFunc(input => {
  173. let dkim = mail.data.dkim ? new DKIM(mail.data.dkim) : this.dkim;
  174. this.logger.debug(
  175. {
  176. tnx: 'DKIM',
  177. messageId: mail.message.messageId(),
  178. dkimDomains: dkim.keys.map(key => key.keySelector + '.' + key.domainName).join(', ')
  179. },
  180. 'Signing outgoing message with %s keys',
  181. dkim.keys.length
  182. );
  183. return dkim.sign(input, mail.data._dkim);
  184. });
  185. }
  186. this.transporter.send(mail, (...args) => {
  187. if (args[0]) {
  188. this.logger.error(
  189. {
  190. err: args[0],
  191. tnx: 'transport',
  192. action: 'send'
  193. },
  194. 'Send Error: %s',
  195. args[0].message
  196. );
  197. }
  198. callback(...args);
  199. });
  200. });
  201. });
  202. return promise;
  203. }
  204. getVersionString() {
  205. return util.format('%s (%s; +%s; %s/%s)', packageData.name, packageData.version, packageData.homepage, this.transporter.name, this.transporter.version);
  206. }
  207. _processPlugins(step, mail, callback) {
  208. step = (step || '').toString();
  209. if (!this._userPlugins.hasOwnProperty(step)) {
  210. return callback();
  211. }
  212. let userPlugins = this._userPlugins[step] || [];
  213. let defaultPlugins = this._defaultPlugins[step] || [];
  214. if (userPlugins.length) {
  215. this.logger.debug(
  216. {
  217. tnx: 'transaction',
  218. pluginCount: userPlugins.length,
  219. step
  220. },
  221. 'Using %s plugins for %s',
  222. userPlugins.length,
  223. step
  224. );
  225. }
  226. if (userPlugins.length + defaultPlugins.length === 0) {
  227. return callback();
  228. }
  229. let pos = 0;
  230. let block = 'default';
  231. let processPlugins = () => {
  232. let curplugins = block === 'default' ? defaultPlugins : userPlugins;
  233. if (pos >= curplugins.length) {
  234. if (block === 'default' && userPlugins.length) {
  235. block = 'user';
  236. pos = 0;
  237. curplugins = userPlugins;
  238. } else {
  239. return callback();
  240. }
  241. }
  242. let plugin = curplugins[pos++];
  243. plugin(mail, err => {
  244. if (err) {
  245. return callback(err);
  246. }
  247. processPlugins();
  248. });
  249. };
  250. processPlugins();
  251. }
  252. /**
  253. * Sets up proxy handler for a Nodemailer object
  254. *
  255. * @param {String} proxyUrl Proxy configuration url
  256. */
  257. setupProxy(proxyUrl) {
  258. let proxy = urllib.parse(proxyUrl);
  259. // setup socket handler for the mailer object
  260. this.getSocket = (options, callback) => {
  261. let protocol = proxy.protocol.replace(/:$/, '').toLowerCase();
  262. if (this.meta.has('proxy_handler_' + protocol)) {
  263. return this.meta.get('proxy_handler_' + protocol)(proxy, options, callback);
  264. }
  265. switch (protocol) {
  266. // Connect using a HTTP CONNECT method
  267. case 'http':
  268. case 'https':
  269. httpProxyClient(proxy.href, options.port, options.host, (err, socket) => {
  270. if (err) {
  271. return callback(err);
  272. }
  273. return callback(null, {
  274. connection: socket
  275. });
  276. });
  277. return;
  278. case 'socks':
  279. case 'socks5':
  280. case 'socks4':
  281. case 'socks4a': {
  282. if (!this.meta.has('proxy_socks_module')) {
  283. return callback(new Error('Socks module not loaded'));
  284. }
  285. let connect = ipaddress => {
  286. let proxyV2 = !!this.meta.get('proxy_socks_module').SocksClient;
  287. let socksClient = proxyV2 ? this.meta.get('proxy_socks_module').SocksClient : this.meta.get('proxy_socks_module');
  288. let proxyType = Number(proxy.protocol.replace(/\D/g, '')) || 5;
  289. let connectionOpts = {
  290. proxy: {
  291. ipaddress,
  292. port: Number(proxy.port),
  293. type: proxyType
  294. },
  295. [proxyV2 ? 'destination' : 'target']: {
  296. host: options.host,
  297. port: options.port
  298. },
  299. command: 'connect'
  300. };
  301. if (proxy.auth) {
  302. let username = decodeURIComponent(proxy.auth.split(':').shift());
  303. let password = decodeURIComponent(proxy.auth.split(':').pop());
  304. if (proxyV2) {
  305. connectionOpts.userId = username;
  306. connectionOpts.password = password;
  307. } else if (proxyType === 4) {
  308. connectionOpts.userid = username;
  309. } else {
  310. connectionOpts.authentication = {
  311. username,
  312. password
  313. };
  314. }
  315. }
  316. socksClient.createConnection(connectionOpts, (err, info) => {
  317. if (err) {
  318. return callback(err);
  319. }
  320. return callback(null, {
  321. connection: info.socket || info
  322. });
  323. });
  324. };
  325. if (net.isIP(proxy.hostname)) {
  326. return connect(proxy.hostname);
  327. }
  328. return dns.resolve(proxy.hostname, (err, address) => {
  329. if (err) {
  330. return callback(err);
  331. }
  332. connect(Array.isArray(address) ? address[0] : address);
  333. });
  334. }
  335. }
  336. callback(new Error('Unknown proxy configuration'));
  337. };
  338. }
  339. _convertDataImages(mail, callback) {
  340. if ((!this.options.attachDataUrls && !mail.data.attachDataUrls) || !mail.data.html) {
  341. return callback();
  342. }
  343. mail.resolveContent(mail.data, 'html', (err, html) => {
  344. if (err) {
  345. return callback(err);
  346. }
  347. let cidCounter = 0;
  348. html = (html || '').toString().replace(/(<img\b[^>]* src\s*=[\s"']*)(data:([^;]+);[^"'>\s]+)/gi, (match, prefix, dataUri, mimeType) => {
  349. let cid = crypto.randomBytes(10).toString('hex') + '@localhost';
  350. if (!mail.data.attachments) {
  351. mail.data.attachments = [];
  352. }
  353. if (!Array.isArray(mail.data.attachments)) {
  354. mail.data.attachments = [].concat(mail.data.attachments || []);
  355. }
  356. mail.data.attachments.push({
  357. path: dataUri,
  358. cid,
  359. filename: 'image-' + ++cidCounter + '.' + mimeTypes.detectExtension(mimeType)
  360. });
  361. return prefix + 'cid:' + cid;
  362. });
  363. mail.data.html = html;
  364. callback();
  365. });
  366. }
  367. set(key, value) {
  368. return this.meta.set(key, value);
  369. }
  370. get(key) {
  371. return this.meta.get(key);
  372. }
  373. }
  374. module.exports = Mail;