Last active
January 24, 2019 10:13
-
-
Save qunabu/df93583e6512616130e0266b10a901a8 to your computer and use it in GitHub Desktop.
Node.js dummy email queue, when SMTP fails
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
/** | |
|--------| | |
/--X--| SMTP 1 | | |
/ ^ |--------| | |
/ \--- Retry with next provider | |
|----------------|/ |--------| |------------------| | |
| Mail | ---X--> | SMTP 2 | /->| ^_^ Happy user | | |
|----------------|\ ^ |--------| / |------------------| | |
\ \--- Retry / | |
\ |--------| / | |
\---->| SMTP 3 |--/ | |
|--------| | |
// EXMAPLE | |
EmailQueue.sendEmail({ | |
to: '[email protected]', | |
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 = { | |
'[email protected]':'smtps://[email protected]:[email protected]', | |
'[email protected]':'smtps://[email protected]:[email protected]', | |
'[email protected]':'smtps://[email protected]:[email protected]' | |
}; | |
// 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