从不同主机发送电子邮件的重试机制
Retry mechanism to send an email from different host
我正在使用 nodemailer
发送电子邮件,如果发送失败,我想使用其他主机重试。
我试过了:
let tries = 0;
let maxTries = 2;
const sendEmail = async () => {
tries += 1;
if (tries === maxTries) return;
const transporter = nodemailer.createTransport({
host: tries === 1 ? host1 : host2,
port: port,
secure: false
});
// mailOptions object here....
await transporter.sendMail(mailOptions, (err, info) => {
if (err) {
return sendEmail();
} else {
console.log('Email Sent Successfuly');
}
});
}
可以用但是感觉有点麻烦
有没有更好的方法来实现这个功能?
这样的事情怎么样(根据 Bergi 的建议更新)?
const sendEmail = async (mailOptions, hosts = [host1, host2]) => {
if (hosts .length == 0) {
return Promise .reject ('all hosts failed')
}
// configure transporter
try {
const info = await transporter .sendMail (mailOptions);
return 'Email sent successfully';
} catch (err) {
return sendEmail (option, hosts .slice (1))
}
}
(请不要使用这个原始版本,因为 Bergi 指出的原因)
// DO NOT USE
const sendEmail = async (options, hosts = [host1, host2]) => {
if (hosts .length == 0) {
return Promise .reject ('all hosts failed')
}
// configure transporter
return new Promise ((resolve, reject) => {
transporter .sendMail (mailOptions, (err, info) => {
if (err) {
return sendEmail (option, hosts .slice (1))
} else {
resolve ('Email Sent Successfuly');
}
})
})
}
它可以很容易地扩展以处理类似的事情:
const hosts = [{host: host1, tries: 3}, {host: host2, tries: 1}, {host: host3, tries: 5}]
sendMail (options, hosts)
这样它会尝试第一个主机三次,然后第二个主机一次,然后第三个主机五次,然后放弃。
我正在使用 nodemailer
发送电子邮件,如果发送失败,我想使用其他主机重试。
我试过了:
let tries = 0;
let maxTries = 2;
const sendEmail = async () => {
tries += 1;
if (tries === maxTries) return;
const transporter = nodemailer.createTransport({
host: tries === 1 ? host1 : host2,
port: port,
secure: false
});
// mailOptions object here....
await transporter.sendMail(mailOptions, (err, info) => {
if (err) {
return sendEmail();
} else {
console.log('Email Sent Successfuly');
}
});
}
可以用但是感觉有点麻烦
有没有更好的方法来实现这个功能?
这样的事情怎么样(根据 Bergi 的建议更新)?
const sendEmail = async (mailOptions, hosts = [host1, host2]) => {
if (hosts .length == 0) {
return Promise .reject ('all hosts failed')
}
// configure transporter
try {
const info = await transporter .sendMail (mailOptions);
return 'Email sent successfully';
} catch (err) {
return sendEmail (option, hosts .slice (1))
}
}
(请不要使用这个原始版本,因为 Bergi 指出的原因)
// DO NOT USE
const sendEmail = async (options, hosts = [host1, host2]) => {
if (hosts .length == 0) {
return Promise .reject ('all hosts failed')
}
// configure transporter
return new Promise ((resolve, reject) => {
transporter .sendMail (mailOptions, (err, info) => {
if (err) {
return sendEmail (option, hosts .slice (1))
} else {
resolve ('Email Sent Successfuly');
}
})
})
}
它可以很容易地扩展以处理类似的事情:
const hosts = [{host: host1, tries: 3}, {host: host2, tries: 1}, {host: host3, tries: 5}]
sendMail (options, hosts)
这样它会尝试第一个主机三次,然后第二个主机一次,然后第三个主机五次,然后放弃。