UNPKG

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