UNPKG

2.6 kBJavaScriptView Raw
1/*!
2 * @package @coolgk/utils
3 * @version 2.1.5
4 * @link https://github.com/coolgk/node-utils
5 * @license MIT
6 * @author Daniel Gong <daniel.k.gong@gmail.com>
7 *
8 * Copyright (c) 2017 Daniel Gong <daniel.k.gong@gmail.com>. All rights reserved.
9 * Licensed under the MIT License.
10 */
11
12"use strict";
13/*!
14 * Copyright (c) 2017 Daniel Gong <daniel.k.gong@gmail.com>. All rights reserved.
15 * Licensed under the MIT License.
16 */
17Object.defineProperty(exports, "__esModule", { value: true });
18const emailjs = require("emailjs");
19const mime_types_1 = require("mime-types");
20const path_1 = require("path");
21const string_1 = require("@coolgk/string");
22class Email {
23 constructor(options = { host: 'localhost' }) {
24 this._emailClient = options.emailClient ?
25 options.emailClient : emailjs.server.connect(options);
26 this._stripTags = options.stripTags || string_1.stripTags;
27 this._getMimeType = options.getMimeType || mime_types_1.lookup;
28 }
29 send(options) {
30 ['cc', 'bcc', 'from', 'to'].forEach((field) => {
31 if (options[field]) {
32 options[field] = this._formatEmailAddress(field === 'from' ? [options[field]] : options[field]);
33 }
34 });
35 if (options.attachments) {
36 options.attachments.forEach((attachment) => {
37 if (!attachment.name) {
38 attachment.name = path_1.basename(attachment.path);
39 }
40 if (!attachment.type) {
41 attachment.type = this._getMimeType(attachment.path) || undefined;
42 }
43 });
44 }
45 const sendOptions = Object.assign({}, options, { text: this._stripTags(options.message), attachment: [
46 {
47 data: options.message,
48 alternative: true
49 },
50 ...(options.attachments || [])
51 ] });
52 return new Promise((resolve, reject) => {
53 delete sendOptions.message;
54 delete sendOptions.attachments;
55 this._emailClient.send(sendOptions, (error, message) => {
56 error ? reject(error) : resolve(message);
57 });
58 });
59 }
60 _formatEmailAddress(emails) {
61 const formattedEmails = [];
62 emails.forEach((email) => {
63 if (typeof email === 'string') {
64 email = { email };
65 }
66 formattedEmails.push(`"${email.name || email.email}" <${email.email}>`);
67 });
68 return formattedEmails.join(', ');
69 }
70}
71exports.Email = Email;
72exports.default = Email;