From d4748a3cb20900700b7c9d6a67b3342f263d9882 Mon Sep 17 00:00:00 2001 From: Zack Schuster Date: Fri, 30 Oct 2020 14:37:59 -0700 Subject: [PATCH] smtp/client: add sendAsync api --- smtp/client.ts | 17 +++++++++++++++++ test/client.ts | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) diff --git a/smtp/client.ts b/smtp/client.ts index e3b4133..7042e99 100644 --- a/smtp/client.ts +++ b/smtp/client.ts @@ -72,6 +72,23 @@ export class SMTPClient { }); } + /** + * @public + * @param {Message} msg the message to send + * @returns {Promise} a promise that resolves to the fully processed message + */ + public sendAsync(msg: Message) { + return new Promise((resolve, reject) => { + this.send(msg, (err, msg) => { + if (err != null) { + reject(err); + } else { + resolve(msg); + } + }); + }); + } + /** * @public * @description Converts a message to the raw object used by the internal stack. diff --git a/test/client.ts b/test/client.ts index 1d6488d..a5c66e7 100644 --- a/test/client.ts +++ b/test/client.ts @@ -373,3 +373,51 @@ test('client send can have result awaited when promisified', async (t) => { t.fail(err); } }); + +test('client sendAsync can have result awaited', async (t) => { + const msg = { + subject: 'this is a test TEXT message from emailjs', + from: 'piglet@gmail.com', + bcc: 'pooh@gmail.com', + text: "It is hard to be brave when you're only a Very Small Animal.", + }; + + try { + const message = await client.sendAsync(new Message(msg)); + t.true(message instanceof Message); + t.like(message, { + alternative: null, + content: 'text/plain; charset=utf-8', + text: "It is hard to be brave when you're only a Very Small Animal.", + header: { + bcc: 'pooh@gmail.com', + from: 'piglet@gmail.com', + subject: '=?UTF-8?Q?this_is_a_test_TEXT_message_from_emailjs?=', + }, + }); + t.deepEqual(message.attachments, []); + t.true(isRFC2822Date(message.header.date as string)); + t.regex(message.header['message-id'] as string, /^<.*[@]{1}.*>$/); + } catch (err) { + t.fail(err); + } +}); + +test('client sendAsync can have error caught when awaited', async (t) => { + const msg = { + subject: 'this is a test TEXT message from emailjs', + from: 'piglet@gmail.com', + bcc: 'pooh@gmail.com', + text: "It is hard to be brave when you're only a Very Small Animal.", + }; + + try { + const invalidClient = new SMTPClient({ host: 'bar.baz' }); + const message = await invalidClient.sendAsync(new Message(msg)); + t.true(message instanceof Message); + t.fail(); + } catch (err) { + t.true(err instanceof Error); + t.pass(); + } +});