1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 | "use strict";
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | Object.defineProperty(exports, "__esModule", { value: true });
|
18 | const emailjs = require("emailjs");
|
19 | const mime_types_1 = require("mime-types");
|
20 | const path_1 = require("path");
|
21 | const string_1 = require("@coolgk/string");
|
22 | class 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 | }
|
71 | exports.Email = Email;
|
72 | exports.default = Email;
|