我正在开发一个向用户发送电子邮件的功能,我已经有了我的发送邮件功能,它可以发送给单个用户。我现在正在尝试发送给数组中的多个用户。
我正在用 Typescript 写作,我使用 mailgun 作为我的电子邮件服务提供商
这是一个示例发送邮件功能:
const data = {
from: '[email protected]',
to: '[email protected]',
subject: 'Sample subject',
html: await email(), // I am getting the email template here
}
await mailgun.messages().send(data)
使用上面的代码,我向单个用户发送电子邮件。下面的 json 显示了我如何接收电子邮件列表:
[
{
"name": "User 1",
"email": "[email protected]"
},
{
"name": "user 2",
"email": "[email protected]"
}
]
我希望能够发送给多个用户,并且我想以聪明的方式做到这一点。如果可能,请建议使用代码的最佳解决方案。
谢谢你。
假设send
函数是async
并返回一个承诺:
async function sendMail(){
const myRecipients = [
{
"name": "User 1",
"email": "[email protected]"
},
{
"name": "user 2",
"email": "[email protected]"
}
]
const fromAddress = "[email protected]"
// map our recipient array to the message format expected by `send`
const myMessages = myRecipients.map(r => ({
from: fromAddress,
to: r.email,
subject: "somesubject",
html: "some html"
}))
// map our messages to a bunch of "in-flight" promises
const promises = myMessages.map(m => mailgun.messages().send(m))
// wait for all the promises to complete
await Promise.all(promises)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句