这是我最终得到的解决方案,并认为它更简单,并且可能对人们有所帮助。
请注意个性化对象的形状差异。
收件人可以看到对方:
const sgMail = require('@sendgrid/mail')
sgMail.setApiKey(process.env.SENDGRID_API_KEY)
// Declare the content we'll use for the email
const FROM_EMAIL = 'example@example.io' // <-- Replace with your email
const subject = 'Test Email Subject'
const body = '<p>Hello HTML world!</p>'
const recipients = ['alice@example.com', 'bob@example.com'] // <-- Add your email(s) here to test
// Create the personalizations object that will be passed to our message object
let personalizations = [{
to: [],
subject
}]
// Iterate over our recipients and add them to the personalizations object
for (let index in recipients) {
personalizations[0].to[index] = { email: recipients[index] }
}
const msg = {
personalizations,
from: FROM_EMAIL,
html: body,
}
// Log to see what our message object looks like
console.log(msg)
// Send the email, if success log it, else log the error message
sgMail.send(msg)
.then(() => console.log('Mail sent successfully'))
.catch(error => console.error(error.toString()))
个性化对象:
{
personalizations: [{
to: [
{email: "alice@example.com"},
{email: "bob@example.com"},
],
subject: "Test Email Subject"
}]
}
收件人无法看到对方:
// Create the personalizations object that will be passed to our message object
personalizations = []
// Iterate over our recipients and add them to the personalizations object
for (let index in recipients) {
personalizations[index] = { to: recipients[index], subject}
}
个性化对象:
{
personalizations: [
{
to: "alice@example.com",
subject: "Test Email Subject"
},
{
to: "bob@example.com",
subject: "Test Email Subject"
}
]
}
我创建了一个带有完整解决方案的RunKit,您可以在其中对其进行测试。