NetSuite Send an email to all users who have a specific role in suite script

Sample script that send emails for all users according to their roles. Search for all employees with a particular role, then loop through them to send the email.

/**
 *  @NAPIVersion 2.0
 *  @NModuleScope Public
 */
define(['N/email', 'N/search'], function(email, search) {
  function sendEmailToRole(emailObject, roleId) {
    var employeeIds = getEmployeesByRole(roleId);
    employeeIds.forEach(function(employeeId) {
      emailObject.recipients = employeeId;
      email.send(emailObject)
    });
  }

  function getEmployeesByRole(roleId) {
    var results = search.create({
      type: 'employee',
      filters: [
        ['isinactive', 'is', 'F'],
        'and', ['role', 'anyof', roleId]
      ]
    }).run().getRange({ start: 0, end: 1000 });

    return (results || []).map(function(result) {
      return result.id;
    })
  }

  return {
    sendEmailToRole: sendEmailToRole
  };
});
/**
 *  @NAPIVersion 2.0
 *  @NModuleScope Public
 *  @NScriptType ScheduledScript
 */
define(['./emailUtils'], function(emailUtils) {
  function execute() {
    var ADMINISTRATOR = 3;

    var email = {
      author: 1073,
      subject: 'SUBJ: This is a test email',
      body: 'This is the body of the test email',
    };

    emailUtils.sendEmailToRole(email, ADMINISTRATOR);
  }

  return {
    execute: execute
  }
});

Leave a comment

Your email address will not be published. Required fields are marked *