SSJS Core

SSJS Core
Home Page

Server-Side JavaScript (SSJS) Core Library Functions


Write an SSJS code block to retrieve account details

<script runat="server" language="JavaScript" executioncontexttype="GET" >
  // Load the Core library
  Platform.Load("Core", "1");

  try {
    var account = {
      QueryAllAccounts: true,
      Filter: {
        Property: "CustomerKey",
        SimpleOperator: "equals",
        Value: "xxxxx-xxxx-xxxx-xxxx-xxxxxx"
      }
    };

    // Retrieve the Account
    var results = Account.Retrieve(account);

    // Check if results contain any data
    if (results && results.length > 0) {
      // Output the Name and other details of the first result
      Write("Name: " + results[0].Name + "\n");
      Write("Address: " + results[0].Address + "\n");
      Write("City: " + results[0].City + "\n");
      Write("Country: " + results[0].Country + "\n");
      Write("BusinessName: " + results[0].BusinessName + "\n");
    } else {
      Write("No account found with the specified CustomerKey.\n");
    }
  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + "\n");
    Write("Error Description: " + ex.description + "\n");
  }
</script>


Write an SSJS block to retrieve tracking

<script runat="server" language="JavaScript" executioncontexttype="GET" >
  // Load the Core library with version 1
  Platform.Load("Core", "1");

  try {
    // Define the filter as an object correctly
    var filter = { 
      Property: "CustomerKey",
      SimpleOperator: "equals",
      Value: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx"
    };

    // Attempt to retrieve tracking information for the specified account
    var acctTracking = Account.Tracking.Retrieve(filter);

    // Uncomment the line below to see the complete tracking information as a string
    // Write(Stringify(acctTracking));

    // Output tracking information for the account
    Write('\n\nTracking information about the account:\n\n');

    // Check if acctTracking has data to avoid runtime errors
    if (acctTracking && acctTracking.length > 0) {
      // Loop through the retrieved tracking data for the account
      for (var i = 0; i < acctTracking.length; i++) {
        // Output Sends information
        Write("Sends:\n");
        Write("\t\tTotal: " + acctTracking[i].Sends.Total + "\n");

        // Output Bounces information
        Write("Bounces:\n");
        Write("\t\tTotal: " + acctTracking[i].Bounces.Total + "\n");
        Write("\t\tHardBounces: " + acctTracking[i].Bounces.HardBounces + "\n");
        Write("\t\tSoftBounces: " + acctTracking[i].Bounces.SoftBounces + "\n");
        Write("\t\tBlockBounces: " + acctTracking[i].Bounces.BlockBounces + "\n");
        Write("\t\tTechnicalBounces: " + acctTracking[i].Bounces.TechnicalBounces + "\n");
        Write("\t\tUnknownBounces: " + acctTracking[i].Bounces.UnknownBounces + "\n");

        // Output Clicks information
        Write("Clicks:\n");
        Write("\t\tTotal: " + acctTracking[i].Clicks.Total + "\n");
        Write("\t\tUnique: " + acctTracking[i].Clicks.Unique + "\n");

        // Output Opens information
        Write("Opens:\n");
        Write("\t\tTotal: " + acctTracking[i].Opens.Total + "\n");
        Write("\t\tUnique: " + acctTracking[i].Opens.Unique + "\n");

        // Output Unsubscribes information
        Write("Unsubscribes:\n");
        Write("\t\tUnique: " + acctTracking[i].Unsubscribes.Unique + "\n");
      }
    } else {
      Write("No tracking information found for the specified CustomerKey.\n");
    }
  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>

                            


Write an SSJS block to update Account

<script runat="server">
  // Load the Core library with version 1
  Platform.Load("core", "1");

  try {
    // Initialize an Account object with the specified CustomerKey
    // You need to have required roles and permission As a Administrator 
    var myAccount = Account.Init("9xxxxxD-5xx2-4xx4-BxxF-Fxxxxxxxx1");

    // Update the City property of the specified Account
    var status = myAccount.Update({ "City": "Edinburg" });

    // Define a filter for retrieving the updated Account with a specific CustomerKey
    var filter = {
      Property: "CustomerKey",
      SimpleOperator: "equals",
      Value: "9xxxxxD-5xx2-4xx4-BxxF-Fxxxxxxxx1"
    };

    // Retrieve the updated Account based on the defined filter
    var results = Account.Retrieve(filter);

    // Uncomment the line below to see the complete results as a string
    // Write(Stringify(results));

    // Output the update status
    Write('Status: ' + status + '\n');

    // Output information about the updated Account
    Write('Name: ' + results[0].Name + '\n');
    Write('Address: ' + results[0].Address + '\n');
    Write('City: ' + results[0].City + '\n');
    Write('Country: ' + results[0].Country + '\n');
    Write('BusinessName: ' + results[0].BusinessName + '\n');
    Write('Email: ' + results[0].Email + '\n');
    Write('City: ' + results[0].City + '\n');
  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>

                            


Write an SSJS block to retrieve account user details

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1.1.1");

  try {
    // Retrieve an Account User based on the CustomerKey
    // Should be parent BU and have required permissions as Administrator
    var accountUser = AccountUser.Retrieve({
      Property: "CustomerKey",
      SimpleOperator: "equals",
      Value: "68c534ec-20af-438e-b36a-f459cff6642d"
    });

    // Uncomment the line below to see the complete AccountUser object as a string
    // Write(Stringify(accountUser));

    // Output information about the retrieved Account User
    Write('Client ID: ' + accountUser[0].Client.ID + '\n');
    Write('UserID: ' + accountUser[0].UserID + '\n');
  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                            


Write an SSJS block to update account user password

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1.1.1");

  try {
    // Retrieve an Account User based on the UserID
    var accountUser = AccountUser.Retrieve({
      Property: "UserID",
      SimpleOperator: "equals",
      Value: "SPrasad"
    });

    // Initialize an AccountUser object with the CustomerKey and ClientID
    var acctUser = AccountUser.Init(accountUser[0].CustomerKey, accountUser[0].Client.ID);

    // Update the password of the specified Account User
    var status = acctUser.Update({ "Password": "Password@12345$" });

    // Uncomment the line below to see the complete AccountUser object as a string
    // Write(Stringify(accountUser));

    // Output the update status
    Write('Status: ' + status + '\n');

    // Retrieve the updated Account User information
    var updatedAccountUser = AccountUser.Retrieve({
      Property: "UserID",
      SimpleOperator: "equals",
      Value: "SPrasad"
    });

    // Output information about the updated Account User
    Write('Client ID: ' + updatedAccountUser[0].Client.ID + '\n');
    Write('UserID: ' + updatedAccountUser[0].UserID + '\n');
    Write('CustomerKey: ' + updatedAccountUser[0].CustomerKey + '\n');
  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                            


Write an SSJS block to deactivate account user

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Retrieve an Account User based on the UserID
    var accountUser = AccountUser.Retrieve({
      Property: "UserID",
      SimpleOperator: "equals",
      Value: "SPrasad"
    });

    // Initialize an AccountUser object with the CustomerKey and ClientID
    var acctUser = AccountUser.Init(accountUser[0].CustomerKey, accountUser[0].Client.ID);

    // Deactivate the specified Account User
    var status = acctUser.Deactivate();
    //var status = acctUser.Activate();

    // Uncomment the line below to see the complete AccountUser object as a string
    // Write(Stringify(accountUser));

    // Output the update status
    Write('Deactivation Status: ' + status + '\n');

    // Retrieve the updated Account User information
    var updatedAccountUser = AccountUser.Retrieve({
      Property: "UserID",
      SimpleOperator: "equals",
      Value: "SPrasad"
    });

    // Output information about the deactivated Account User
    Write('Client ID: ' + updatedAccountUser[0].Client.ID + '\n');
    Write('UserID: ' + updatedAccountUser[0].UserID + '\n');
    Write('CustomerKey: ' + updatedAccountUser[0].CustomerKey + '\n');
  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                            


Write an SSJS block to create an account user

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    var newUser = {
      "Name" : "Shashi Prasad",
      "UserID" : "shashi.prasad_ampscriptify",
      "Password" : "PassWord$1234@",
      "Email" : "shashi.prasad@ampscriptify.com",
      "ClientID" : 100009000,
      "DefaultBusinessUnitKey": "AEA84DD4-FBCD-467E-BC03-0F38E6D600B0",
      "AssociatedBusinessUnits" : ["AEA84DD4-FBCD-467E-BC03-0F38E6D600B0"]
  };
  
    var status = AccountUser.Add(newUser);

    // Output the update status
    Write('Status: ' + status + '\n');

    // Retrieve the updated Account User information
    var updatedAccountUser = AccountUser.Retrieve({
      Property: "UserID",
      SimpleOperator: "equals",
      Value: "shashi.prasad_ampscriptify"
    });

    // Output information about the deactivated Account User
    Write('Client ID: ' + updatedAccountUser[0].Client.ID + '\n');
    Write('UserID: ' + updatedAccountUser[0].UserID + '\n');
    Write('CustomerKey: ' + updatedAccountUser[0].CustomerKey + '\n');
  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                            


Write an SSJS block to create a data extension

<script runat="server">
  // Load the Core library with version 1
  Platform.Load("Core", "1");

  try {
    // Define the properties of the Data Extension to be created
    var deObj = {
      "CustomerKey": "Dataview_SentDE",
      "Name": "Dataview_SentDE",
      "Fields": [
        { "Name": "AccountID", "FieldType": "Number" },
        { "Name": "OYBAccountID", "FieldType": "Number" },
        { "Name": "JobID", "FieldType": "Number" },
        { "Name": "ListID", "FieldType": "Number" },
        { "Name": "BatchID", "FieldType": "Number" },
        { "Name": "SubscriberID", "FieldType": "Number" },
        { "Name": "SubscriberKey", "FieldType": "Text", "MaxLength": 254 },
        { "Name": "EventDate", "FieldType": "Date" },
        { "Name": "Domain", "FieldType": "Text", "MaxLength": 128 },
        { "Name": "TriggererSendDefinitionObjectID", "FieldType": "Text", "MaxLength": 36 },
        { "Name": "TriggeredSendCustomerKey", "FieldType": "Text", "MaxLength": 36 }
      ]
    };

    // Create the Data Extension
    var myDE = DataExtension.Add(deObj);

    // Output the created Data Extension details
    Write(Stringify(myDE));
  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                            


Write an SSJS block to retrieve a data extension properties

<script runat="server">
  // Load the Core library with version 1
  Platform.Load("Core", "1");

  try {
    // Retrieve the Data Extension details based on CustomerKey
    var results = DataExtension.Retrieve({
      Property: "CustomerKey",
      SimpleOperator: "equals",
      Value: "Dataview_Sent"
    });

    // Output the retrieved Data Extension details
    Write("Name: " + results[0].Name + '\n');
    Write("Description: " + results[0].Description + '\n');
    Write("IsSendable: " + results[0].IsSendable + '\n');
    Write("IsTestable: " + results[0].IsTestable + '\n');
    Write("CategoryID: " + results[0].CategoryID + '\n');
    Write("IsPlatformObject: " + results[0].IsPlatformObject + '\n');
    Write("CustomerKey: " + results[0].CustomerKey + '\n');
    Write("CreatedDate: " + results[0].CreatedDate + '\n');
    Write("ModifiedDate: " + results[0].ModifiedDate + '\n');
    Write("ObjectID: " + results[0].ObjectID + '\n');
    Write("Status: " + results[0].Status + '\n');
    Write("Client Id: " + results[0].Client.ID + '\n');
  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                            


Write an SSJS block to create a senable data extension

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1.1.1");

  try {
    // Define the properties of the Sendable Data Extension to be created
    var deObj = {
      "CustomerKey": "SendableDE",
      "Name": "SendableDE",
      "Fields": [
        { "Name": "AccountID", "FieldType": "Number" },
        { "Name": "OYBAccountID", "FieldType": "Number" },
        { "Name": "JobID", "FieldType": "Number" },
        { "Name": "ListID", "FieldType": "Number" },
        { "Name": "BatchID", "FieldType": "Number" },
        { "Name": "SubscriberID", "FieldType": "Number" },
        { "Name": "SubscriberKey", "FieldType": "Text", "MaxLength": 254 },
        { "Name": "EventDate", "FieldType": "Date" },
        { "Name": "Domain", "FieldType": "Text", "MaxLength": 128 },
        { "Name": "TriggererSendDefinitionObjectID", "FieldType": "Text", "MaxLength": 36 },
        { "Name": "TriggeredSendCustomerKey", "FieldType": "Text", "MaxLength": 36 }
      ],
      "SendableInfo": {
        "Field": { "Name": "SubscriberKey", "FieldType": "Text" },
        "RelatesOn": "Subscriber Key"
      },
      "IsTestable": true
    };

    // Create the Sendable Data Extension
    var myDE = DataExtension.Add(deObj);

    // Output the created Sendable Data Extension details
    Write(Stringify(myDE));
  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>

                         


Write an SSJS block to add a new attribute to a data extension

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Initialize the existing Sendable Data Extension
    var de = DataExtension.Init('SendableDE');

    // Define the properties of the new field to be added
    var newField = {
      Name: "NewField",
      CustomerKey: "CustomerKey", // Specify the desired CustomerKey for the new field
      FieldType: "Number",
      IsRequired: true,
      DefaultValue: "100"
    };

    // Add the new field to the Sendable Data Extension
    var status = de.Fields.Add(newField);

    // Output the status of adding the new field
    Write((status));
  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>

                         


Write an SSJS block to retrieve attributes from a data extension

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1.1.1");

  try {
    // Initialize the existing Sendable Data Extension
    var de = DataExtension.Init('SendableDE');
    
    // Retrieve the fields of the Data Extension
    var fields = de.Fields.Retrieve();

    // Loop through each field and output information
    for (var i = 0; i < fields.length; i++) {
      Write("Name: " + fields[i].Name + '\n');
      Write("FieldType: " + fields[i].FieldType + '\n');
      Write("IsPrimaryKey: " + fields[i].IsPrimaryKey + '\n');
      Write("MaxLength: " + fields[i].MaxLength + '\n');
      Write("Ordinal: " + fields[i].Ordinal + '\n');
      Write("DefaultValue: " + fields[i].DefaultValue + '\n');
      Write("StorageType: " + fields[i].StorageType + '\n');
      Write("==========================\n");
    }
  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>

                         


Write an SSJS block to update sendable field from a data extension

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Initialize the existing Sendable Data Extension
    var updateDE = DataExtension.Init('SendableDE');

    var status = updateDE.Fields.UpdateSendableField("SubscriberID", "Subscriber ID");

    // Output the status of adding the new field
    Write((status));
  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>

                         


Write an SSJS block to add records into a data extension

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Initialize the existing Sendable Data Extension
    var updateDE = DataExtension.Init('SendableDE');

    // Define an array of contacts to be added
    var arrContacts = [
      { JobID: 1234, SubscriberKey: "sprasad@example.com", EventDate: "11/29/2023" },
      { JobID: 5678, SubscriberKey: "shashi@example.com", EventDate: "11/29/2023" }
    ];

    // Add the rows to the Data Extension
    var status = updateDE.Rows.Add(arrContacts);

    // Output the status of adding the new rows
    Write("Add Rows Status: " + status + '\n');
  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                         


Write an SSJS block to update records into a data extension

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Initialize the existing Sendable Data Extension
    var updateDE = DataExtension.Init('SendableDE');

    
    // Update the rows to the Data Extension
    var status = updateDE.Rows.Update({"BatchID":1234,"Domain":"Gmail.com"}, ["JobID"], [1234]);

   // Output the status of adding the new rows
   Write("Add Rows Status: " + status + '\n');
  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                         


Write an SSJS block to remove a record from a data extension

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Initialize the existing Sendable Data Extension
    var updateDE = DataExtension.Init('SendableDE');

    
    // Update the rows to the Data Extension
    var status = updateDE.Rows.Remove(["Domain", "BatchID"], ["Gmail.com", 1234]);

   // Output the status of adding the new rows
   Write("Removed Rows Status: " + status + '\n');
  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                         


Write an SSJS block to retrieve records from a data extension

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Initialize the existing Sendable Data Extension
    var DE = DataExtension.Init('SendableDE');

    // Retrieve all rows from the Data Extension
    var data = DE.Rows.Retrieve();

    // Output the field values for each row
    for (var i = 0; i < data.length; i++) {
      Write("JobID: " + data[i].JobID + "\n");
      Write("BatchID: " + data[i].BatchID + "\n");
      Write("EventDate: " + data[i].EventDate + "\n");
      Write("========================================= \n");
    }
  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                         


Write an SSJS block to retrieve records from a data extension with simple filter

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Initialize the existing Sendable Data Extension
    var DE = DataExtension.Init('SendableDE');

    // Define the filter condition
    var filter = { Property: "JobID", SimpleOperator: "greaterThan", Value: 1234 };

    // Retrieve rows from the Data Extension based on the filter
    var data = DE.Rows.Retrieve(filter);

    // Output the field values for each filtered row
    for (var i = 0; i < data.length; i++) {
      Write("JobID: " + data[i].JobID + "\n");
      Write("BatchID: " + data[i].BatchID + "\n");
      Write("EventDate: " + data[i].EventDate + "\n");
      Write("========================================= \n");
    }
  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                         


Write an SSJS block to retrieve records from a data extension with complex filter

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Initialize the existing Sendable Data Extension
    var DE = DataExtension.Init('SendableDE');

    // Define the filter condition
    var complexfilter = {
      LeftOperand:{
          Property:"JobID",
          SimpleOperator:"greaterThan",
          Value:1234
      },
      LogicalOperator:"AND",
      RightOperand:{
          Property:"EventDate",
          SimpleOperator:"equals",
          Value:"11/29/2023"
}};

    // Retrieve rows from the Data Extension based on the filter
    var data = DE.Rows.Retrieve(complexfilter);

    // Output the field values for each filtered row
    for (var i = 0; i < data.length; i++) {
      Write("JobID: " + data[i].JobID + "\n");
      Write("BatchID: " + data[i].BatchID + "\n");
      Write("EventDate: " + data[i].EventDate + "\n");
      Write("========================================= \n");
    }
  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                         


Write an SSJS block to create a delivery profile

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    var newDP = {
      "Name" : "Newsletter",
      "CustomerKey" : "Newsletter",
      "Description" : "An SSJS Added Profile",
      "SourceAddressType" : "DefaultPrivateIPAddress"
  };

    // Use DeliveryProfile.Add to add a new Delivery Profile
    var newProfile = DeliveryProfile.Add(newDP);

    // Doesn't return any status but a wsdl 
    Write(newProfile);
  
  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                         


Write an SSJS block to update a delivery profile

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Initialize the existing Delivery Profile
    var myProfile = DeliveryProfile.Init('Newsletter');

    // Update the name of the Delivery Profile
    var status = myProfile.Update({ "Name" : "Weekly Newsletter" });

    // Output the updated Delivery Profile details or relevant information
    Write("Update Status: " + status + '\n');
  
  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                         


Write an SSJS block to remove a delivery profile

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Initialize the existing Delivery Profile
    var myProfile = DeliveryProfile.Init('Newsletter');

    // Update the name of the Delivery Profile
    var status = myProfile.Remove();

    // Output the updated Delivery Profile details or relevant information
    Write("Update Status: " + status + '\n');
  
  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                         


Write an SSJS block to retreive bounce events

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    var sendID = 854897;
    var filter = { Property:"SendID", SimpleOperator:"equals", Value:sendID };
    var bounces = BounceEvent.Retrieve(filter);
    //Write(Stringify(bounces));

    for (i=0;i<bounces.length;i++){
      Write("SMTPCode :" + bounces[i].SMTPCode + "\n");
      Write("BounceCategory :" + bounces[i].BounceCategory + "\n");
      Write("SMTPReason :" + bounces[i].SMTPReason + "\n");
      Write("BounceType :" + bounces[i].BounceType + "\n");
      Write("SendIDSpecified :" + bounces[i].SendIDSpecified + "\n");
      Write("SubscriberKey :" + bounces[i].SubscriberKey + "\n");
      Write("EventDate :" + bounces[i].EventDate + "\n");
      Write("EventType :" + bounces[i].EventType + "\n");
      Write("CreatedDate :" + bounces[i].CreatedDate + "\n");
      Write("ModifiedDate :" + bounces[i].ModifiedDate + "\n");
      Write("TriggeredSendDefinitionObjectID :" + bounces[i].TriggeredSendDefinitionObjectID + "\n");
      Write("============================================================ \n");
    }
  
  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                         


Write an SSJS block to retreive not sent events

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    var sendID = 648890;
    var filter = { Property:"SendID", SimpleOperator:"equals", Value:sendID };
    var notSends = NotSentEvent.Retrieve(filter);
    //Write(Stringify(notSends));

    for (i=0;i<notSends.length;i++){
      Write("SubscriberKey :" + notSends[i].SubscriberKey + "\n");
      Write("EventDate :" + notSends[i].EventDate + "\n");
      Write("TriggeredSendDefinitionObjectID :" + notSends[i].TriggeredSendDefinitionObjectID + "\n");
      Write("BatchID :" + notSends[i].BatchID + "\n");
      Write("SubscriberID :" + notSends[i].PartnerProperties[1].Value + "\n");
      Write("CreatedDate :" + notSends[i].CreatedDate + "\n");
      Write("============================================================ \n");
    }
  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                         


Write an SSJS block to retreive sent events

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    var sendID = 854897;
    var filter = { Property:"SendID", SimpleOperator:"equals", Value:sendID };
    var sends = SentEvent.Retrieve(filter);
    //Write(Stringify(sends));

    
    for (i=0;i<sends.length;i++){
      Write("SubscriberKey :" + sends[i].SubscriberKey + "\n");
      Write("EventDate :" + sends[i].EventDate + "\n");
      Write("TriggeredSendDefinitionObjectID :" + sends[i].TriggeredSendDefinitionObjectID + "\n");
      Write("BatchID :" + sends[i].BatchID + "\n");
      Write("SubscriberID :" + sends[i].PartnerProperties[1].Value + "\n");
      Write("ListID :" + sends[i].PartnerProperties[0].Value + "\n");
      Write("CreatedDate :" + sends[i].CreatedDate + "\n");
      Write("============================================================ \n");
    }

  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>

                         


Write an SSJS block to retreive unsub events

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    //var sendID = 854897;
    //var filter = { Property:"SendID", SimpleOperator:"equals", Value:sendID };
    var sends = UnsubEvent.Retrieve();
    //Write(Stringify(sends));

    
    for (i=0;i<sends.length;i++){
      Write("SubscriberKey :" + sends[i].SubscriberKey + "\n");
      Write("EventDate :" + sends[i].EventDate + "\n");
      Write("TriggeredSendDefinitionObjectID :" + sends[i].TriggeredSendDefinitionObjectID + "\n");
      Write("BatchID :" + sends[i].BatchID + "\n");
      Write("CreatedDate :" + sends[i].CreatedDate + "\n");
      Write("============================================================ \n");
    }

  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                         


Write an SSJS block to retreive open events

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    //var sendID = 854897;
    //var filter = { Property:"SendID", SimpleOperator:"equals", Value:sendID };
    var sends = OpenEvent.Retrieve();
    //Write(Stringify(sends));

    
    for (i=0;i<sends.length;i++){
      Write("SubscriberKey :" + sends[i].SubscriberKey + "\n");
      Write("EventDate :" + sends[i].EventDate + "\n");
      Write("TriggeredSendDefinitionObjectID :" + sends[i].TriggeredSendDefinitionObjectID + "\n");
      Write("BatchID :" + sends[i].BatchID + "\n");
      Write("CreatedDate :" + sends[i].CreatedDate + "\n");
      Write("============================================================ \n");
    }

  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                         


Write an SSJS block to retreive click events

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Retrieve all click events
    var clicks = ClickEvent.Retrieve();

    // Output details for each click event
    for (var i = 0; i < clicks.length; i++) {
      Write("SubscriberKey: " + clicks[i].SubscriberKey + "\n");
      Write("EventDate: " + clicks[i].EventDate + "\n");
      Write("TriggeredSendDefinitionObjectID: " + clicks[i].TriggeredSendDefinitionObjectID + "\n");
      Write("BatchID: " + clicks[i].BatchID + "\n");
      Write("CreatedDate: " + clicks[i].CreatedDate + "\n");
      Write("ModifiedDate: " + clicks[i].ModifiedDate + "\n");
      Write("URLID: " + clicks[i].URLID + "\n");
      Write("URL: " + clicks[i].URL + "\n");
      Write("============================================================ \n");
    }

  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>

                         


Write an SSJS block to retreive filter definition

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Retrieve the filter definition with CustomerKey equal to "Behavioral"
    var results = FilterDefinition.Retrieve({
      Property: "CustomerKey",
      SimpleOperator: "equals",
      Value: "Behavioral"
    });

    // Output details for each retrieved filter definition
    for (var i = 0; i < results.length; i++) {
      Write("Name: " + results[i].Name + "\n");
      Write("Description: " + results[i].Description + "\n");
      Write("ObjectID: " + results[i].ObjectID + "\n");
      Write("CategoryID: " + results[i].CategoryID + "\n");
      Write("CreatedDate: " + results[i].CreatedDate + "\n");
      Write("ModifiedDate: " + results[i].ModifiedDate + "\n");
      Write("DataFilter: " + results[i].DataFilter + "\n");
      Write("DataSource CustomerKey: " + results[i].DataSource.CustomerKey + "\n");
      Write("DataSource Name: " + results[i].DataSource.Name + "\n");
      Write("============================================================\n");
    }

  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                         


Write an SSJS block to create filter definition with simple filter

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Define the filter criteria for the filter definition
    var filterObj = {
      Property: "Industry",
      SimpleOperator: "equals",
      Value: "Insurance"
    };

    // Define the new filter definition
    var newFD = {
      Name: "Insurance_Filter",
      CustomerKey: "Insurance_Filter",
      Filter: filterObj,
      DataSource: {
        Type: "DataExtension",
        CustomerKey: "478F3177-15D9-4BD9-9099-4AA6B6CFF914"
      }
    };

    // Attempt to add the new filter definition
    var status = FilterDefinition.Add(newFD);

    // Output the status as a string (for debugging purposes)
    Write(Stringify(status));

  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                         


Write an SSJS block to create filter definition with complex filter

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Define the filter criteria for the filter definition
     var filterObj = {
      LeftOperand: {
        Property: "Industry",
        SimpleOperator: "equals",
        Value: "Insurance"
      },
      LogicalOperator: "AND",
      RightOperand: {
        Property: "Country",
        SimpleOperator: "equals",
        Value: "Spain"
      }
    };

    // Define the new filter definition
    var newFD = {
      Name: "Insurance_Filter_v1",
      CustomerKey: "Insurance_Filter_1",
      Filter: filterObj,
      DataSource: {
        Type: "DataExtension",
        CustomerKey: "478F3177-15D9-4BD9-9099-4AA6B6CFF914"
      }
    };

    // Attempt to add the new filter definition
    var status = FilterDefinition.Add(newFD);

    // Output the status as a string (for debugging purposes)
    Write(Stringify(status));

  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>

                         


Write an SSJS block to update filter definition

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Define the filter criteria for the filter definition
    var fd = FilterDefinition.Init("Insurance_Filter_v1"); 
   
    var status = fd.Update({ "Name": "Updated_Filter_Insurance" });
    //var status=myFD.Remove();

    // Output the status as a string (for debugging purposes)
    Write(Stringify(status));

  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                         


Write an SSJS block to retrieve folder

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Retrieve the folder based on the specified name
    var results = Folder.Retrieve({
      Property: "Name",
      SimpleOperator: "equals",
      Value: "Shashi"
    });

    // Output the details of the retrieved folders
    for (var i = 0; i < results.length; i++) {
      Write("Name: " + results[i].Name + "\n");
      Write("ID: " + results[i].ID + "\n");
      Write("ContentType: " + results[i].ContentType + "\n");
      Write("Description: " + results[i].Description + "\n");
      Write("IsActive: " + results[i].IsActive + "\n");
      Write("IsEditable: " + results[i].IsEditable + "\n");
      Write("AllowChildren: " + results[i].AllowChildren + "\n");
      Write("CustomerKey: " + results[i].CustomerKey + "\n");

      // Check if the folder has a parent folder
      if (results[i].ParentFolder) {
        Write("ParentFolder Name: " + results[i].ParentFolder.Name + "\n");
        Write("ParentFolder ID: " + results[i].ParentFolder.ID + "\n");
        Write("ParentFolder CustomerKey: " + results[i].ParentFolder.CustomerKey + "\n");
      }

      Write("=================================================================== \n");
    }

  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                         


Write an SSJS block to create a folder

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Define the properties of the new folder
    var newFolder = {
      "Name" : "Newsletter 2024",
      "CustomerKey" : "Newsletter_2024",
      "Description" : "Test added",
      "ContentType" : "dataextension",//[asset,journey,automations] //adjust as needed
      "IsActive" : "true",
      "IsEditable" : "true",
      "AllowChildren" : "true",
      "ParentFolderID" : 31853 // Parent folder ID; adjust as needed
    };

    // Add the new folder
    var status = Folder.Add(newFolder);

    // Output the status of the folder addition
    Write(status);

  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                         


Write an SSJS block to update a folder

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Define the properties of the new folder
    var myFolder = Folder.Init("Newsletter_2024");
    var status = myFolder.Update({ "Name" : "2. Newsletter 2024" });
    //var status=myFolder.Remove();
    

    // Output the status of the folder addition
    Write(status);

  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                         


Write an SSJS block to retrieve lists

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Retrieve all lists
    var lists = List.Retrieve();

    // Output the status of the folder addition
    //Write(Stringify(lists));

    for (i = 0; i < lists.length; i++) {
      Write("CustomerKey: " + lists[i].CustomerKey + "\n");
      Write("ID: " + lists[i].ID + "\n");
      Write("ListName: " + lists[i].ListName + "\n");
      Write("Category: " + lists[i].Category + "\n");
      Write("Description: " + lists[i].Description + "\n");
      Write("Type: " + lists[i].Type + "\n");
      Write("ListClassification: " + lists[i].ListClassification + "\n");
      Write("CreatedDate: " + lists[i].CreatedDate + "\n");
      Write("ModifiedDate: " + lists[i].ModifiedDate + "\n");
      Write("======================================\n");
    }

  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                         


Write an SSJS block to retrieve subscribers from a list

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Initialize a list with the external key "NewEvents - 31855"
    var myList = List.Init('NewEvents - 31855');

    // Define a filter for retrieving subscribers with "Status" equals "Active"
    var filter = { Property: "Status", SimpleOperator: "equals", Value: "Active" };

    // Retrieve subscribers based on the defined filter
    var subs = myList.Subscribers.Retrieve(filter);

    // Output the retrieved subscribers
    // Write(Stringify(subs));

    // Loop through the retrieved subscribers and output details
    for (i = 0; i < subs.length; i++) {
      Write("ID: " + subs[i].ID + "\n");
      Write("EmailAddress: " + subs[i].EmailAddress + "\n");
      Write("SubscriberKey: " + subs[i].SubscriberKey + "\n");
      Write("Status: " + subs[i].Status + "\n");
      Write("CreatedDate: " + subs[i].CreatedDate + "\n");
      Write("UnsubscribedDate: " + subs[i].UnsubscribedDate + "\n");
    }

  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                         


Write an SSJS block to add subscribers from a list

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Initialize a list with the external key "NewEvents - 31855"
    var myList = List.Init('NewEvents - 31855');

    // Define the subscriber details
    var subscriber = {
      "EmailAddress": "ampscriptify@gmail.com",
      "SubscriberKey": "ampscriptify@gmail.com"
    };

    // Add the subscriber to the list
    var status = myList.Subscribers.Add(subscriber);

    // Output the status of the subscriber addition
    Write(Stringify(status));

  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                         


Write an SSJS block to update subscriber's status to Unsubscribe from a list

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Initialize a list with the external key "NewEvents - 31855"
    var myList = List.Init('NewEvents - 31855');

    // Define the subscriber details, including the "Status" field
    var subscriber = {
      "EmailAddress": "ampscriptify@gmail.com",
      "SubscriberKey": "ampscriptify@gmail.com"
    };

    // Update the subscriber to the list
    // The first param should have a email address attribute and the second parameter is the updated status
    var status = myList.Subscribers.Update(subscriber,"Unsubscribed");

    // Output the status of the subscriber addition
    Write(Stringify(status));

  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                         


Write an SSJS block to upsert subscriber's profile attribute to a list

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Initialize a list with the external key "NewEvents - 31855"
    var myList = List.Init('NewEvents - 31855');

    // Define the subscriber details, including the "Status" field
    var subscriber = {
      "EmailAddress": "ampscriptify@gmail.com",
      "SubscriberKey": "ampscriptify@gmail.com"
    };

    // Update the subscriber to the list
    // The first param should have a email address attribute and the second parameter is the profile attribute(s)
    // Upsert do-not update the status irrespective of what you pass as part of subscriber attribute
    // By default the status is set to "Active", be careful while leveraging Upsert
    var status = myList.Subscribers.Upsert(subscriber,{"City":"Barcelona"});

    // Output the status of the subscriber addition
    Write(Stringify(status));

  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>

                         


Write an SSJS block to retrieve subscriber's tracking from a list

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Initialize a list with the external key "NewEvents - 31855"
    var myList = List.Init('NewEvents - 31855');

    // Define the filter for the subscriber
    var filter = {
      Property: "SubscriberKey",
      SimpleOperator: "equals",
      Value: "ampscriptify@gmail.com"
    };

    // Retrieve tracking data for the specified subscriber
    var results = myList.Subscribers.Tracking.Retrieve(filter);

    // Output the retrieved tracking data
    Write(Stringify(results));

  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>


                         


Write an SSJS block to unsubscribe subscriber from a list

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Initialize a list with the external key "NewEvents - 31855"
    var myList = List.Init('NewEvents - 31855');

    // Define the subscriber details
    var subscriber = {
      "EmailAddress": "ampscriptify@gmail.com",
      "SubscriberKey": "ampscriptify@gmail.com"
    };

    // Unsubscribe the subscriber
    var results = myList.Subscribers.Unsubscribe(subscriber);

    // Output the result of the unsubscribe operation
    Write(Stringify(results));

  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>

                         


Write an SSJS block to retreive query definition

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Retrieve all Query Definitions
    var results = QueryDefinition.Retrieve();

    // Output the result of the retrieve operation
    //Write(Stringify(results));

    for(i=0;i<results.length;i++){
      Write("Name :"+results[i].Name+"\n");
      Write("ObjectID :"+results[i].ObjectID+"\n");
      Write("QueryText :"+results[i].QueryText+"\n");
      Write("TargetType :"+results[i].TargetType+"\n");
      Write("TargetUpdateType :"+results[i].TargetUpdateType+"\n");
      Write("CategoryID :"+results[i].CategoryID+"\n");
      Write("CustomerKey :"+results[i].CustomerKey+"\n");
      Write("CreatedDate :"+results[i].CreatedDate+"\n");
      Write("ModifiedDate :"+results[i].ModifiedDate+"\n");
      Write("DataExtensionTarget Name :"+results[i].DataExtensionTarget.Name+"\n");
      Write("DataExtensionTarget CustomerKey :"+results[i].DataExtensionTarget.CustomerKey+"\n");
      Write("======================================================================\n");
    }

  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>


                         


Write an SSJS block to update query definition

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Initialize a Query Definition with the external key "bouncedataviewQueryDef"
    var qd = QueryDefinition.Init("bouncedataviewQueryDef");

    // Define the new properties for the Query Definition
    var definition = {
      Name: "Bounce Data View Query Definition v1",
      QueryText: "Select * from [_Bounce] where IsUnique=1"
    };

    // Update the Query Definition with the new properties
    var status = qd.Update(definition);

    // Output the status of the update operation
    Write("Update Status: " + status + '\n');

  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                         


Write an SSJS block to perform query definition

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Initialize a Query Definition with the external key "bouncedataviewQueryDef"
    var qd = QueryDefinition.Init("bouncedataviewQueryDef");
    var status = qd.Perform();
   // var status = qd.Remove();

    // Output the status of the update operation
    Write("Update Status: " + status + '\n');

  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>

                         


Write an SSJS block to add query definition

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Define the Query Definition properties
    var queryDef = {
      Name: "Holidays v1",
      CustomerKey: "Holidays_v1",
      TargetUpdateType: "Update",
      TargetType: "DE",
      Target: {
        Name: "SFMC Demo",
        CustomerKey: "14EBC368-41A6-4E59-89C9-A5F2C38EAA7B"
      },
      QueryText: "SELECT Forename, Surname, Industry, Company, Email, SubscriberKey FROM [SFMC Demo]"
    };

    // Add the Query Definition
    var status = QueryDefinition.Add(queryDef);

    // Output the status
    Write("Status: " + status + '\n');

  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>

                         


Write an SSJS block to update send classification

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Initialize the Send Classification with the external key 'Default Commercial'
    var sc = SendClassification.Init('Default Commercial');

    // Define the updated Send Classification properties
    var updatedSC = {
      "Name": "Commercial Sends",
      "SenderProfileKey":"1142",
      "DeliveryProfileKey": "Default"
    };

    // Update the Send Classification
    var status = sc.Update(updatedSC);

    // Output the status of the update
    Write(Stringify(status));

  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>


                         


Write an SSJS block to add send classification

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Define the properties for the new Send Classification
    var newSC = {
      "CustomerKey": "Shashi Newsletter", // Specify a unique customer key for the new Send Classification
      "Name": "Shashi Newsletter",
      "Description": "Test SSJS description",
      "SenderProfileKey": "1142", // Replace with the correct CustomerKey for the Sender Profile
      "DeliveryProfileKey": "Default" // Replace with the correct CustomerKey for the Delivery Profile
    };

    // Add the new Send Classification
    var status = SendClassification.Add(newSC);

    // Output the status of the update
    Write(Stringify(status));

  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                         


Write an SSJS block to remove send classification

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Define the properties for Send Classification
    var sc = SendClassification.Init('Shashi Newsletter');
    var status = sc.Remove();

    // Output the status of the update
    Write(Stringify(status));

  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                         


Write an SSJS block to retrieve subscribers

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Retrieve information about subscribers
    var results = Subscriber.Retrieve();

    // Output the status of the update
    //Write(Stringify(results));

    // Loop through the results and output subscriber details
    for (i = 0; i < results.length; i++) {
      Write("EmailAddress: " + results[i].EmailAddress + "\n");
      Write("SubscriberKey: " + results[i].SubscriberKey + "\n");
      Write("UnsubscribedDate: " + results[i].UnsubscribedDate + "\n");
      Write("ID: " + results[i].ID + "\n");
      Write("Status: " + results[i].Status + "\n");
    }

  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>

                         


Write an SSJS block to add a subscriber

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Define the new subscriber details
    var newSubscriber = {
      "EmailAddress": "abc@gmail.com",
      "SubscriberKey": "20100730001",
      "Lists": {"Status": "Active", "ID": 10280, "Action": "Create"}
    };

    // Add the new subscriber
    var status = Subscriber.Add(newSubscriber);

    // Output the status of the subscriber addition
    Write(status);

  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>


                         


Write an SSJS block to upsert a subscriber

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Define the new subscriber details
    var newSubscriber = {
      "EmailAddress": "abc@gmail.com",
      "SubscriberKey": "20100730001",
      "Lists": {"Status": "Unsubscribed", "ID": 10280, "Action": "Upsert"}
    };

    var subObj = Subscriber.Init(newSubscriber.SubscriberKey);
    var status = subObj.Upsert(newSubscriber);

    // Output the status of the subscriber addition
    Write(status);

  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                         


Write an SSJS block to update a subscriber

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Define the updated subscriber details
    var subscriber = {
      "EmailTypePreference": "HTML",
      "Attributes": {"City": "Barcelona"}
    };

    // Initialize an existing subscriber with the specified SubscriberKey
    var subObj = Subscriber.Init("20100730001");

    // Update the subscriber with the new information
    var status = subObj.Update(subscriber);

    // Output the status of the subscriber update
    Write(status);

  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                         


Write an SSJS block to unsubscribe a subscriber

<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Initialize an existing subscriber with the specified SubscriberKey
    var subObj = Subscriber.Init("20100730001");

    // Update the subscriber with the new information
    var status = subObj.Unsubscribe();

    // Output the status of the subscriber update
    Write(status);

  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>

                         


Write an SSJS block to remove a subscriber

<script runat="server">
<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Initialize an existing subscriber with the specified SubscriberKey
    var subObj = Subscriber.Init("20100730001");

    // Remove the subscriber
    var status = subObj.Remove();

    // Output the status of the subscriber removal
    Write(Stringify(status));

  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>


                         


Write an SSJS block to add security events for the audit trail access log


<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Initialize the existing Sendable Data Extension
    var updateDE = DataExtension.Init('Security_Events');

    // Define an array of contacts to be added
    var arrContacts = [
      { SecurityEventTypeID: 1, SecurityEventType: "Login Attempted", Description: "Duplicate values can be present when users log in from different machines, or when viewed using spreadsheet software that truncates milliseconds from time values." },
      { SecurityEventTypeID: 2, SecurityEventType: "Security Question Answered", Description: "" },
      { SecurityEventTypeID: 3, SecurityEventType: "Password Changed", Description: "" },
      { SecurityEventTypeID: 4, SecurityEventType: "Administrator Access", Description: "A member of the Salesforce Support team has logged in to the account as an account user." },
      { SecurityEventTypeID: 5, SecurityEventType: "Administrator Unlock", Description: "An administrator unlocked a user." },
      { SecurityEventTypeID: 6, SecurityEventType: "Redirect", Description: "For users provisioned with IMH Redirect flow, the user is redirected to CAS pages and they try to log in from Members." },
      { SecurityEventTypeID: 7, SecurityEventType: "Security Setting Changed Impersonation", Description: "" },
      { SecurityEventTypeID: 8, SecurityEventType: "Logout", Description: "" },
      { SecurityEventTypeID: 9, SecurityEventType: "Request Authorization Code", Description: "" }
    ];

    // Add the rows to the Data Extension
    var status = updateDE.Rows.Add(arrContacts);

    // Output the status of adding the new rows
    Write("Add Rows Status: " + status + '\n');
  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                         
                         


Write an SSJS block to add login status for the audit trail access log



<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Initialize the existing Sendable Data Extension
    var updateDE = DataExtension.Init('Login Status');

    // Define an array of contacts to be added
    var arrContacts = [
      { LoginStatusID: 0, LoginStatusName: "AccountDisabled", Description: "The account is disabled." },  
      { LoginStatusID: 1, LoginStatusName: "Failed", Description: "The login attempt failed." },
      { LoginStatusID: 2, LoginStatusName: "MustChangePassword", Description: "The user's password has expired and must be changed." },
      { LoginStatusID: 3, LoginStatusName: "NotSet", Description: "The login status hasn’t been set" },
      { LoginStatusID: 4, LoginStatusName: "Successful", Description: "The login was successful." },
      { LoginStatusID: 5, LoginStatusName: "UserAccountDisabled", Description: "The user's account is disabled." },
      { LoginStatusID: 6, LoginStatusName: "InMaintenance", Description: "The login was unsuccessful because of a maintenance event." },
      { LoginStatusID: 7, LoginStatusName: "UsernamePasswordLock", Description: "The user account was locked because they entered an incorrect password too many times." },
      { LoginStatusID: 8, LoginStatusName: "SecurityQuestionAnswerLock", Description: "The user account was locked because they entered incorrect security question answers too many times." },
      { LoginStatusID: 9, LoginStatusName: "BusinessUnitDisabled", Description: "The Business Unit account is no longer active." },
      { LoginStatusID: 10, LoginStatusName: "SystemDBUnavailable", Description: "An internal database error occurred in the process of verifying a user." },
      { LoginStatusID: 11, LoginStatusName: "AccountLocked", Description: "The account is locked." },
      { LoginStatusID: 12, LoginStatusName: "FailedNotOnWhitelist", Description: "" },
      { LoginStatusID: 13, LoginStatusName: "FailedInvalidActivationLink", Description: "The login failed because the user clicked an invalid or expired activation link." },
      { LoginStatusID: 14, LoginStatusName: "FailedDeviceNotActivated", Description: "Unable to activate the device using two-factor authentication." },
      { LoginStatusID: 15, LoginStatusName: "FailedDeviceNotActivateNeedMobile", Description: "The login failed because the user's device isn’t activated as required by the account's security settings, and a mobile number is required for SMS verification." },
      { LoginStatusID: 16, LoginStatusName: "FailedSsoOnlyLogin", Description: "Single Sign-On (SSO) is required to log in to the account, but the user attempted to log in using a different method." },
      { LoginStatusID: 17, LoginStatusName: "SecurityActivationCodeLock", Description: "The user has been locked out from using their username or password, security question or answer, and activation code." },
      { LoginStatusID: 18, LoginStatusName: "MustChangePasswordNoIDV", Description: "The user must change their password." },
      { LoginStatusID: 19, LoginStatusName: "InvalidCasApplication", Description: "" },
      { LoginStatusID: 20, LoginStatusName: "Logout", Description: "The user logged out." },
      { LoginStatusID: 21, LoginStatusName: "AppNotAuthorized", Description: "The app wasn't authorized using the OAuth2 Authorize API." }
    ];

    // Add the rows to the Data Extension
    var status = updateDE.Rows.Add(arrContacts);

    // Output the status of adding the new rows
    Write("Add Rows Status: " + status + '\n');
  } catch (ex) {
    // Handle any exceptions and output the error details
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                            
                         


Write an SSJS block to delete a record from a data extension where an attribute is null.



<script runat="server">
  // Load the Core library with version 1.1.1
  Platform.Load("Core", "1");

  try {
    // Initialize the existing Sendable Data Extension using its external key
    var DE = DataExtension.Init('4908DC08-78E3-46AC-87D2-BE6D2B36C49B');

    // Retrieve all rows from the Data Extension
    var data = DE.Rows.Retrieve();

    // Loop through each row in the Data Extension
    for (var i = 0; i < data.length; i++) {
      // Get the value of the "Sends" attribute for the current row
      var nullAttribute = data[i].Sends;

      // Get the value of the "MonthEnding" attribute for the current row
      var MonthEnding = data[i].MonthEnding;

      // Check if the "Sends" attribute is null or undefined
      if (!nullAttribute) {
        // Remove the row where "MonthEnding" matches the current row's value
        var status = DE.Rows.Remove(["MonthEnding"], [MonthEnding]);
        
        // Output the status of the row removal operation
        Write(status);
      }
    }
  } catch (ex) {
    // Catch any exceptions that occur and output the error message and description
    Write("Error Message: " + ex.message + '\n');
    Write("Error Description: " + ex.description + '\n');
  }
</script>
                         



Comments

Most Viewed

CLOUD PAGE ENABLEMENT - PART 1

EMAIL NOT SENT IN JOURNEY BUILDER

CONSIDERATIONS FOR JOURNEY BUILDER

Understanding Transactional Messaging

Preference Center Demystified


Knowledge Article

Popular Posts

CLOUD PAGE ENABLEMENT - PART 1

EMAIL NOT SENT IN JOURNEY BUILDER

CONSIDERATIONS FOR JOURNEY BUILDER

Understanding Transactional Messaging

Preference Center Demystified

Journey Builder REST API Documentation

Share with Friends

Disclaimer:

The information provided on this technical blog is for general informational purposes only. As a SFMC (Salesforce Marketing Cloud) Technical Architect, I strive to offer accurate and up-to-date content related to SFMC and its associated technologies. However, please note that technology is constantly evolving, and the information provided may become outdated or inaccurate over time.

The content published on this blog represents my personal views and experiences as a SFMC Technical Architect and does not necessarily reflect the official views or opinions of any organization or employer I may be affiliated with.

While I make every effort to ensure the accuracy and reliability of the information presented, I cannot guarantee its completeness, suitability, or applicability to your specific circumstances. Therefore, it is essential to verify any information provided and make your own independent assessments or seek professional advice if needed.

Furthermore, any actions taken based on the information provided on this blog are at your own risk. I shall not be held liable for any damages, losses, or inconveniences arising from the use of the information presented here.

Please keep in mind that SFMC and its associated technologies are complex and require technical expertise for proper implementation and management. It is recommended to consult with qualified professionals or official SFMC documentation for comprehensive guidance.

Finally, please note that any product or company names mentioned on this blog are trademarks or registered trademarks of their respective owners. The mention of these trademarks or registered trademarks does not imply any endorsement or affiliation with the blog.

By accessing and using this blog, you agree to the terms of this disclaimer. If you do not agree with any part of this disclaimer, please refrain from using this blog.