Send Email to User Groups
To run this code above, you need to:
- Install
@roq/nodejs
anddotenv
npm packages. - Get the credentials from ROQ Console and put them in the
.env
file. - Make sure there is an email template in ROQ Console with key name
market-research-group-email
. Please, go to this tutorial to create an email template.
ROQ GraphQL Query
In business applications, it is often necessary to communicate with specific user groups based on their characteristics or behavior. To accomplish this task, we can utilize GraphQL or the User Groups and Mails APIs.
It's easy to query user groups using GraphQL:
query {
userGroups {
totalCount
data {
id
name
reference
users {
totalCount
data {
id
email
}
}
}
}
}
We need to filter the response data to obtain the email addresses of users belonging to a particular group. Once we have the required email data, we can use the sendEmail()
API to send emails to the group.
Here's the simple code how to achieve such a task using ROQ Node.js SDK and GraphQL query:
import 'dotenv/config'
import { Platform } from '@roq/nodejs'
/**
* Connect to the ROQ Platform
*/
const roqClient = new Platform({
apiKey: process.env.ROQ_API_KEY,
environmentId: process.env.ROQ_ENVIRONMENT_ID,
host: process.env.ROQ_PLATFORM_URL
})
const query = `
{
userGroups {
totalCount
data {
id
name
reference
users {
totalCount
data {
id
email
}
}
}
}
}
`
const roqGraphQLRequest = await roqClient.asSuperAdmin().graphqlRequest(query);
The ROQ Node.js SDK provide API to run a GraphQL query natively, its' called graphqlRequest
, so you don't need to add any additional packages. For more information about this API, please read the GraphQL Query documentation.
Send Emails
To send emails we can use one of the user group IDs and filter users emails.
// Suppose you have the group IDs as follows:
const selectedGroupIds = ["554a2843-66dd-4c9a-adc1-0c48484591b6"];
// Filter the groups with the provided IDs.
const selectedGroups = roqGraphQLRequest.data.userGroups.data.filter(group => selectedGroupIds.includes(group.id));
if (selectedGroups.length === 0) {
console.log("No groups found with the provided IDs.");
} else {
// Extract the user emails from the selected groups.
const emails = selectedGroups.flatMap(group => group.users.data.map(user => user.email));
// Send Emails
const emailStatus = await roqClient.asSuperAdmin().sendMail({
mail: {
key: "market-research-group-email",
locale: "en-US",
emails: emails,
data: [
{ key: "name", value: "James Davis" },
{ key: "news_update", value: "the UI Analytics Dashboard is available!" },
{ key: "your_name", value: "Anna W." },
{ key: "your_position", value: "AnyVidz CTO" }
]
}
})
console.log(emailStatus)
}
The email for Market Research group was sent to every group members.