NodeJS Sendgrid问题:无法向多个收件人发送电子邮件

4

我遇到了向多个收件人发送邮件的问题。

我的脚本如下:

var SendGrid = require('sendgrid').SendGrid;
var sendgrid = new SendGrid('<<username>>', '<<password>>');      
    sendgrid.send({
    to: 'nabababa@gmail.com',   
from: 'sengupta.nabarun@gmail.com',
bcc: ["sengupta.nabarun@gmail.com","sengupta_nabarun@rediffmail.com"],

我这里有两个问题

  1. 我可以在收件人列表中使用收件人数组吗?
  2. 如何在密件抄送列表中获取收件人数组?

与上述两个查询相关的解决方案确实会非常有用

谢谢 Nabarun

5个回答

6
您可以在tobcc字段中都使用收件人数组。
例如:
var SendGrid = require('sendgrid').SendGrid;
var sendgrid = new SendGrid('{{sendgrid username}}', '{{sendgrid password}}');      
sendgrid.send({
    to: ['one@example.com', 'two@example.com'],
    from: 'nick@sendgrid.com',
    bcc: ['three@example.com', 'four@example.com'],
    subject: 'This is a demonstration of SendGrid sending email to mulitple recipients.',
    html: '<img src="http://3.bp.blogspot.com/-P6jNF5dU_UI/TTgpp3K4vSI/AAAAAAAAD2I/V4JC33e6sPM/s1600/happy2.jpg" style="width: 100%" />'
});

如果这对您不起作用,而且Node没有输出任何错误,请登录SendGrid网站并查看电子邮件活动日志以查看是否正在发送电子邮件。

我在测试您的代码示例时遇到了一个问题,如果您将tobcc发送到同一个gmail地址,则gmail会将其全部合并为一封电子邮件(因此似乎无法工作)。确保在测试时将电子邮件发送到完全不同的帐户。

如果您需要一些电子邮件帐户进行测试,则Guerrilla Mail是创建临时测试帐户的绝佳选择。


6

这是我最终采用的解决方案,认为它更直接并且对人们有所帮助。

注意个性化对象形状的差异。

收件人可以看到彼此:


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,您可以在其中测试它。


2
新的sendgrid-nodejs更新已经废弃了之前的实现方法,因此先前接受的答案现在将无法帮助您。
所以...只是一个更新,以防有人通过特定的搜索结果进入此线程。
    to: [
      {
        email: 'email1@email.com', 
      },
      {
        email: 'email2@email.com', 
      },
    ],

2

对于Sendgrid的v3 API,我发现他们的“厨房水槽”示例很有帮助。以下是其中的相关部分:

var helper = require('sendgrid').mail

mail = new helper.Mail()
email = new helper.Email("test@example.com", "Example User")
mail.setFrom(email)

mail.setSubject("Hello World from the SendGrid Node.js Library")

personalization = new helper.Personalization()
email = new helper.Email("test1@example.com", "Example User")
personalization.addTo(email)
email = new helper.Email("test2@example.com", "Example User")
personalization.addTo(email)

// ...

mail.addPersonalization(personalization)

1
阅读更多关于Sendgrid的个性化之后,我认为您可以在单个个性化中添加多个收件人。这将发送一封总邮件,其中收件人字段中有2个人,而不是向每个电子邮件发送2封邮件。 - Tyler Collier

1

这是一个针对TypeScript(使用ts版本3.4.3和sendGrid 7.1.1编写的)的解决方案,您不希望收件人能够看到彼此。

import * as sendGrid from '@sendgrid/mail'

type UserEmail = {
  to: string
  subject: string
}
// Add as many recipients as you want
recipients = ['email1@global.com', 'email2@gmail.com']
const personalizations: UserEmail[] = recipients.map(admin => ({
    to: admin,
    subject: 'Inject Subject Here',
}))

try {
    await sendGrid.send({
        from, // Inject
        personalizations,
        html, // Inject
    })
} catch (err) {
    console.log(err)    
}

"const personalizations"看起来像这样。"
[{ to: 'email1@global.com',
    subject: 'Inject Subject Here' },
  { to: 'email2@global.com',
    subject: 'Inject Subject Here' }]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接