diff --git a/__tests__/client/index.test.ts b/__tests__/client/index.test.ts index 00d35d2..ae52a03 100644 --- a/__tests__/client/index.test.ts +++ b/__tests__/client/index.test.ts @@ -7,7 +7,7 @@ let server: SMTPServer; describe('client', () => { // TODO: TLS tests // TODO: Error handling tests - // TODO: Auth tests + // TODO: Auth tests // TODO: Capability tests // TODO: Greeting tests @@ -19,7 +19,7 @@ describe('client', () => { }); describe('SMTPClient', () => { - it('sends emails', () => { + it('should send a message: events', () => { const message = { sender: 'a@localhost', recipients: ['b@localhost'], @@ -40,10 +40,34 @@ describe('client', () => { }); }); }); + + it('should send a message: async/await', () => { + const message = { + sender: 'a@localhost', + recipients: ['b@localhost'], + message: 'Test', + }; + + return new Promise(resolve => { + server.once('connection', connection => { + connection.on('message', msg => { + expect(msg).toMatchObject(message); + resolve(true); + }); + }); + + const fn = async () => { + const client = new SMTPClient({ hostname: HOST, port: PORT }); + await client.connect(); + client.mail(message); + }; + fn(); + }); + }); }); describe('sendmail', () => { - it('sends emails', () => { + it('should send a message', () => { const message = { sender: 'a@localhost', recipients: ['b@localhost'], diff --git a/src/client/index.ts b/src/client/index.ts index c6533bc..4a7a4a9 100644 --- a/src/client/index.ts +++ b/src/client/index.ts @@ -45,6 +45,7 @@ export class SMTPClient extends EventEmitter { private wire: Wire; private capabilities: string[] = []; private maxSize = defaultSize; + private welcomed = false; constructor(options: SMTPClientOptions) { super(); @@ -62,7 +63,7 @@ export class SMTPClient extends EventEmitter { } get connected() { - return this.wire.readable; + return this.wire.readable && this.welcomed; } close(): void { @@ -120,6 +121,7 @@ export class SMTPClient extends EventEmitter { } private async init() { + this.welcomed = false; const welcome = await this.smtpRead(); if (welcome[0] !== 220) { throw new Error( @@ -142,6 +144,7 @@ export class SMTPClient extends EventEmitter { await this.smtpSend('HELO'); } + this.welcomed = true; this.emit('ready'); } @@ -160,14 +163,10 @@ export class SMTPClient extends EventEmitter { } } -function sendTo(options: SMTPClientOptions, message: SMTPMessage) { - return new Promise((resolve, reject) => { - const client = new SMTPClient(options); - client.once('error', reject); - client.on('ready', () => { - client.mail(message).then(resolve).catch(reject); - }); - }); +async function sendTo(options: SMTPClientOptions, message: SMTPMessage) { + const client = new SMTPClient(options); + await client.connect(); + await client.mail(message); } function mx(hostname: string): Promise {