Skip to content

Instantly share code, notes, and snippets.

@qunabu
Last active January 24, 2019 10:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qunabu/df93583e6512616130e0266b10a901a8 to your computer and use it in GitHub Desktop.
Save qunabu/df93583e6512616130e0266b10a901a8 to your computer and use it in GitHub Desktop.
Node.js dummy email queue, when SMTP fails
/**
|--------|
/--X--| SMTP 1 |
/ ^ |--------|
/ \--- Retry with next provider
|----------------|/ |--------| |------------------|
| Mail | ---X--> | SMTP 2 | /->| ^_^ Happy user |
|----------------|\ ^ |--------| / |------------------|
\ \--- Retry /
\ |--------| /
\---->| SMTP 3 |--/
|--------|
// EXMAPLE
EmailQueue.sendEmail({
to: 'test@example.com',
subject: 'You\'ve got an email!',
text: 'Plain text message',
html: '<h1>HTML</h1><p>Styled message</p>'
}, (err) => console.log('email not send', err))
*/
import { Email } from 'meteor/email';
import nodemailer from 'nodemailer';
const EMAIL_SERVERS = {
'email1@exmaple.com':'smtps://email1@example.com:pass@example.com',
'email2@exmaple.com':'smtps://email2@example.com:pass@example.com',
'email3@exmaple.com':'smtps://email3@example.com:pass@example.com'
};
// we need transports
const transports = [];
for (let email in EMAIL_SERVERS) {
let transport = nodemailer.createTransport(EMAIL_SERVERS[email]);
transport.from = email;
transports.push(transport);
};
function sendEmailFromTransport(transportsArr, emailData, callback) {
//if all emails fail track this event
if (transportsArr.length == 0) {
if (typeof callback == 'function') {
callback(emailData);
}
return;
}
//remove the first transporter from the array
let transporter = transportsArr.shift();
//change from so it is same as sending transporter, to bypass SPAM
emailData.from = transporter.from;
transporter.sendMail(emailData, (err) => {
// transporter failed now trying next one;
// timeout is used for performance
if (err) {
Meteor.setTimeout(() => {
sendEmailFromTransport(transportsArr, emailData, callback);
}, 500);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment