nodemailer-mongoose
v0.1.2
Published
Nodemailer with MongoDB Queue
Downloads
1
Maintainers
Readme
nodemailer-mongoose
Nodemailer with a MongoDB queue. nodemailer-mongoose stores mails in the database and nodemailer sends them. This package is mostly useful when you have a large number of messages.
yarn add nodemailer-mongoose
Add a mail to the queue
Multiple clients can send mails without configure a server, as long as they use the same database.
/*
This function adds the message to the queue. It will not delivered directly.
Uses options fom Nodemailer (https://nodemailer.com/message/).
*/
let newQueueItem = await mailer.sendMail({
from: '[email protected]',
to: '[email protected]',
subject: 'nodemailer-mongoose',
text: 'This is the first mail delivered with nodemailer-mongoose.'
});
Deliver mails from the queue
You'll need to set up ONE client with smtp configuration, to process the queue.
/*
Configure the connection to an SMTP server.
Uses options fom Nodemailer (https://nodemailer.com/smtp/). Already uses pooling.
*/
mailer.createTransport({
host: 'smtp.some.mail',
port: 587,
auth: {
user: '[email protected]',
pass: 'sup3rs3cr3tpa55w0rd#'
}
});
/*
This function reads all new mails from the database and try to send them.
Failed mails will be tagged as FAILED.
*/
mailer.deliver(); // delivers the default way (only new mails, refresh the queue every 30 seconds)
mailer.deliver('FAILED', 320); // retry all failed mails every 320 seconds
const agent = mailer.deliver(); // it returns an intverval
clearInterval(intervalID); // so it can be stoped like an interval
Full example
A simple client to save and deliver mails.
import * as mailer from 'nodemailer-mongoose';
// connect to mongodb use options from mongoose.connect()
mailer.connectToDatabase('mongodb://localhost:27017/nodemailer-mongoose');
// configure the connection
mailer.createTransport({
host: 'smtp.some.mail',
port: 587,
auth: {
user: '[email protected]',
pass: 'sup3rs3cr3tpa55w0rd#'
}
});
// start to deliver mails and retry failed ones
mailer.deliver();
mailer.deliver('FAILED', 3600); // 3600sec = 1h
// add a mail to the queue
await mailer.sendMail({
from: '[email protected]',
to: '[email protected]',
subject: 'nodemailer-mongoose',
text: 'This is the first mail delivered with nodemailer-mongoose.'
});
Advanced helpers
/*
This function removes FAILED messages from the queue.
Default are mails at least 720 h old AND three attempts to send them.
*/
await mailer.removeFailed()
await mailer.removeFailed(MAX AGE IN HOURS, MAX SEND TRIES)
/*
This function removes all sent messages from the queue.
*/
await mailer.removeSent()
/*
This function returns all mails by the tag in the queue or history.
SENT -> all succesfully send mails (the message is remove after delivery)
FAILED -> all failed messages
QUEUED -> messages not processed by deliver()
*/
let mails = await mailer.getPerState('SENT')
/*
This is the transporter configured by createTransport().
Use it to attach plugins.
*/
mailer.transporter