Friday, February 15, 2019

User Event Script to Suppress the Email Sent When the 'To Be Emailed = T' and Send a Custom Inline HTML Email with the Transaction


Below is a solution on how to use an email template along with user event script triggered on Before Record Submit to suppress the email sent by the system and send a custom email using nlapiSendEmail.

Create the Email Template
1. Create a new Email Template to be used by the script via Documents > Templates > Email Templates > New
2. Fill out a Name for the Template and the Subject. For the body you may use a File or a Text Editor but make sure you include a custom NL TAG (e.g NLATTACHMENTHTML) which would be used by the script. The tag would be replaced by the value we would assign via script.
3. Save the Email Template and take note of the internal id as this would be used on the nlapiMergeRecord call on the script


Create a User Event script triggered on Before Submit
function userEventBeforeSubmit(type){
      if(type == 'approve'){ 
            // create a variable to check if the email needs to be sent
            var blnSendEmail = nlapiGetFieldValue('tobeemailed');
            // set the tobeemailed field to false to suppress the email sending of the system
            nlapiSetFieldValue('tobeemailed','F');
           
            if(blnSendEmail){
                  var record = nlapiGetRecordId();
                  var sender = nlapiGetFieldValue('employee');
                  var emailrecipients = nlapiGetFieldValue('email');
                  // for multiple emails replace semicolon with comma
                  var recipients = emailrecipients.replace(';',',');
                 
                  // create a print of the transation in HTML format
                  var attachment = nlapiPrintRecord('TRANSACTION',record,'HTML',null);
                  // create a variable that would be used on the template to insert the HTML
                  var nlFieldArray = new Array();
                  nlFieldArray['NLATTACHMENTHTML'] = attachment.getValue();
                 
                  // Merge the transaction
                  var mailRec = nlapiMergeRecord(14,'purchaseorder',record,null,null,nlFieldArray);
                 
                  // attach the email to the record
                  var rec = new Object();
                  rec['transaction'] = record;
                 
                  // send the email
                  nlapiSendEmail(sender,recipients,mailRec.getName(),mailRec.getValue(),null,null,rec);
            }
      }
}

No comments:

Post a Comment