Last active
October 9, 2019 12:01
-
-
Save DonMartin76/b074bc01006f7a0288df7fc16822d6db to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
/* eslint-disable no-console */ | |
// npm i smtp-server | |
// npm i mailparser | |
// https://nodemailer.com/extras/smtp-server/ | |
// https://nodemailer.com/extras/mailparser/ | |
// This is a very very simple SMTP server which you can use e.g. with nodemailer | |
// to test sending out email in a microservice. Just replace the transport, using | |
// something like this: | |
/* | |
const fakeTransport = { | |
host: 'localhost', // or wherever this is running | |
port: 2525, | |
secure: false, | |
ignoreTLS: true, | |
auth: { | |
user: 'doesnot', | |
pass: 'matter' | |
} | |
}; | |
*/ | |
// Create the server with `await createServer()`, get a list of received mails | |
// via `getReceivedEmails()` and reset them via `clearEmails()`. | |
const SmtpServer = require('smtp-server').SMTPServer; | |
const { simpleParser } = require('mailparser'); | |
let _emails = []; | |
function createServer() { | |
return new Promise((resolve, reject) => { | |
const server = new SmtpServer({ | |
allowInsecureAuth: true, | |
onAuth(auth, session, callback) { | |
// Yeah, who needs auth | |
return callback(null, { user: 'auto-user', data: 'not-used' }); | |
}, | |
onData(stream, session, callback) { | |
stream.on('end', callback); | |
(async () => { | |
try { | |
const content = await simpleParser(stream); | |
_emails.push(content); | |
} catch (err) { | |
console.error('PARSING EMAIL FAILED HORRIBLY!'); | |
console.error(err); | |
return callback(err); | |
} | |
})(); | |
} | |
}); | |
// Replace the port if you feel like it. | |
server.listen(2525, (err) => { | |
err ? reject(err) : resolve(); | |
}); | |
}); | |
} | |
function getReceivedEmails() { | |
return _emails; | |
} | |
function clearEmails() { | |
_emails = []; | |
} | |
module.exports = { | |
createServer, | |
getReceivedEmails, | |
clearEmails | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment