UNPKG

@coolgk/utils

Version:

javascript, typescript utility and wrapper functions and classes: array, string, base64, ampq, bcrypt, cache, captcha, csv, email, jwt, number, pdf, tmp, token, unit conversion, url params, session, form data, google sign in, facebook sign in

75 lines (73 loc) 2.65 kB
/*! * @package @coolgk/utils * @version 3.1.4 * @link https://github.com/coolgk/node-utils * @license MIT * @author Daniel Gong <daniel.k.gong@gmail.com> * * Copyright (c) 2017 Daniel Gong <daniel.k.gong@gmail.com>. All rights reserved. * Licensed under the MIT License. */ "use strict"; /*! * Copyright (c) 2017 Daniel Gong <daniel.k.gong@gmail.com>. All rights reserved. * Licensed under the MIT License. */ Object.defineProperty(exports, "__esModule", { value: true }); const emailjs = require("emailjs"); const mime_types_1 = require("mime-types"); const path_1 = require("path"); const string_1 = require("@coolgk/string"); const array_1 = require("@coolgk/array"); class Email { constructor(options = { host: 'localhost' }) { this._emailClient = options.emailClient ? options.emailClient : emailjs.server.connect(options); this._stripTags = options.stripTags || string_1.stripTags; this._getMimeType = options.getMimeType || mime_types_1.lookup; } send(options) { ['cc', 'bcc', 'from', 'to'].forEach((field) => { if (options[field]) { options[field] = this._formatEmailAddress(array_1.toArray(options[field])); } }); if (options.attachments) { array_1.toArray(options.attachments).forEach((attachment) => { if (!attachment.name) { attachment.name = path_1.basename(attachment.path); } if (!attachment.type) { attachment.type = this._getMimeType(attachment.path) || undefined; } }); } const sendOptions = Object.assign({}, options, { text: this._stripTags(options.message), attachment: [ { data: options.message, alternative: true }, ...(options.attachments || []) ] }); return new Promise((resolve, reject) => { delete sendOptions.message; delete sendOptions.attachments; this._emailClient.send(sendOptions, (error, message) => { error ? reject(error) : resolve(message); }); }); } _formatEmailAddress(emails) { const formattedEmails = []; emails.forEach((email) => { if (typeof email === 'string') { email = { email }; } formattedEmails.push(`"${email.name || email.email}" <${email.email}>`); }); return formattedEmails.join(', '); } } exports.Email = Email; exports.default = Email;