Categories
Learning

How to add multiple email address to sendgrid nodejs code?

Hello there, welcome to my random question post.

I was facing small issue to add multiple address to bcc to the sendgrid nodejs example :

What I was tried to do ( which was wrong in accepting as sendgrid bcc parameters value)

let testAccount = {
        emailSubject: subjectMsg,
        emailFrom: `Application <${process.env.CESEmailFrom}>`,
        emailTo: email || process.env.OWNER_TO_EMAIL_ADDRESS,
        emailBcc: process.env.OWNER_EMAIL_ADDRESS //note here
 };

(this is just a payload I am preparing to pass to seng-grid function), process.env.OWNER_EMAIL_ADDRESS was holding values like : email1@testdomain.com, email2@testdomain.com so which is incorrect to pass a comma separated string value.

Instead, we just need to tweak a little at the same bcc, line to pass it as Javascript Array value. Here is the example of working code (note the bcc line in the code below):

let testAccount = {
        //user: process.env.CESUsername,
        //pass: process.env.CESPassword,
        emailSubject: subjectMsg,
        emailFrom: `Kitchen Anak <${process.env.CESEmailFrom}>`,
        emailTo: email || process.env.OWNER_TO_EMAIL_ADDRESS,
        emailBcc: process.env.OWNER_EMAIL_ADDRESS && process.env.OWNER_EMAIL_ADDRESS.split(',') || '',
    };

Using javascript split function, I was able pass it as a array, isn’t that simple? 🙂

Facing other error related to sendgrid bcc option

Along this, I have also then faced error after fixing above, still on my Vercel deployment code, then which was related to sendGrid bcc parameter for multiple email address.

According to sendGrid documentation we should have unique email address for ‘to’, ‘cc’ and ‘bcc’ options while sending email, in my case I was having ‘bcc’ email address set in at ‘to’ option.

Hence, so creating a duplicate error log at API level of code. (attaching screenshot of error occurred) and then fixed it by removing or keeping all the ‘to’ and ‘bcc’ parameters unique! Volia, that simple 🙂

Log error due to sendgrid bcc email address should be unique.

Result after correcting email address successful.

Successful email send log!

Thanks for visiting & Happy Learning!