From d799559261c3ec02995c160ccce5880cbab0dced Mon Sep 17 00:00:00 2001 From: Zack Schuster Date: Fri, 30 Oct 2020 13:47:53 -0700 Subject: [PATCH] smtp/client: invoke callback when send is successful allows awaiting message result when send is promisified --- smtp/client.ts | 3 +++ test/client.ts | 40 +++++++++++++++++++++++++++++++++++++++- 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/smtp/client.ts b/smtp/client.ts index 7b6289f..e3b4133 100644 --- a/smtp/client.ts +++ b/smtp/client.ts @@ -63,6 +63,9 @@ export class SMTPClient { } this.queue.push(stack); this._poll(); + if (this.queue.every((x) => x !== stack)) { + callback(null, message); + } } else { callback(new Error(why), msg); } diff --git a/test/client.ts b/test/client.ts index da13c1e..1dcf571 100644 --- a/test/client.ts +++ b/test/client.ts @@ -4,7 +4,13 @@ import test from 'ava'; import { simpleParser, ParsedMail } from 'mailparser'; import { SMTPServer } from 'smtp-server'; -import { DEFAULT_TIMEOUT, SMTPClient, Message, MessageHeaders } from '../email'; +import { + DEFAULT_TIMEOUT, + SMTPClient, + Message, + MessageHeaders, + isRFC2822Date, +} from '../email'; const parseMap = new Map(); const port = 3000; @@ -309,3 +315,35 @@ test('client only responds once to greylisting', async (t) => { ); t.is(error, "bad response on command 'RCPT': greylist"); }); + +test('client send can have result awaited when promisified', async (t) => { + // bind necessary to retain internal access to client prototype + const sendAsync = promisify(client.send.bind(client)); + + 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 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); + } +});