I am trying to get the contact list and check if the email recipient opened the email or not. I found this code and tried but got 401.
import config from "@server/config"
sgClient.setApiKey(config.sendgridKey)
const headers = {
"on-behalf-of": "my account user name" // I put my account user name here
}
const request = {
url: `/v3/subusers`,
method: "GET"
} as any
const list = await sgClient
.request(request)
.then()
.catch((err) => {
console.log("list", err.response.body)
})
What do I need to put for the header 'on-behalf-of'? What does the subuser's user name? And is there any example to get the 'email opened' event? I am using Node.js.
Thank you!
Twilio SendGrid developer evangelist here.
The API you are trying to use there is the subuser API, not the contacts API. The subuser API is for managing subusers, which are accounts you can apply credit to and send emails from. Subusers are only available on Pro or Premier email accounts or Advanced Marketing Campaign accounts.
However, even if you were to use the Contacts API to get a list of your contacts, that's not the way to see if they have opened an email.
You should instead register for the Event Webhook. With the Event Webhook, SendGrid will send you webhook requests about events that occur as SendGrid processes your emails. These events include "processed", "delivered", "opened", and "clicked" and there are more in the documentation.
To handle the Event Webhook you need to create yourself an endpoint that can receive incoming HTTP requests. Here is an example from the documentation using Express.
const express = require('express');
const app = express();
app.use(express.json());
app.configure(function(){
app.set('port', process.env.PORT || 3000);
});
app.post('/event', function (req, res) {
const events = req.body;
events.forEach(function (event) {
// Here, you now have each event and can process them how you like
processEvent(event);
});
});
var server = app.listen(app.get('port'), function() {
console.log('Listening on port %d', server.address().port);
});