Consider more than one email separator for values in email field to send email

Requirement

Need to consider comma or semicolon as a separator for email ids given in email field for sending out the email .

Solution

Following code provides the way to consider any of the given email separator( , ;).

/**
 * @NApiVersion 2.1
 * @NScriptType MapReduceScript
 */



define(['N/currentRecord', 'N/email', 'N/record', 'N/render', 'N/runtime', 'N/search'],
    /**
     * @param{currentRecord} currentRecord
     * @param{email} email
     * @param{record} record
     * @param{render} render
     * @param{runtime} runtime
     * @param{runtime} search
     */
    (currentRecord, email, record, render, runtime, search) => {
        /**
         * Defines the function that is executed at the beginning of the map/reduce process and generates the input data.
         * @param {Object} inputContext
         * @param {boolean} inputContext.isRestarted - Indicates whether the current invocation of this function is the first
         *     invocation (if true, the current invocation is not the first invocation and this function has been restarted)
         * @param {Object} inputContext.ObjectRef - Object that references the input data
         * @typedef {Object} ObjectRef
         * @property {string|number} ObjectRef.id - Internal ID of the record instance that contains the input data
         * @property {string} ObjectRef.type - Type of the record instance that contains the input data
         * @returns {Array|Object|Search|ObjectRef|File|Query} The input data to use in the map/reduce process
         * @since 2015.2
         */

        const getInputData = (inputContext) => {
            try {
                //InvoiceSearch created to send mail regarding the remainder of payement due before 7 days.
                log.debug('In getinput')
                var invoiceSearchObj = search.create({
                    type: "invoice",
                    filters:
                        [
                            ["type", "anyof", "CustInvc"],
                            "AND",
                            ["mainline", "is", "T"],
                            "AND",
                            ["status", "anyof", "CustInvc:A"],
                            "AND",

                            ["customer.custentity_jj_test_email", "isnotempty", ""],
                            "AND",
                            ["internalid", "anyof", "2442078","2442080","2442081"]
                        ],
                    columns:
                        [
                            search.createColumn({name: "internalid", label: "Internal ID"}),
                            search.createColumn({name: "trandate", label: "Date"}),
                            search.createColumn({name: "tranid", label: "Doc No"}),
                            search.createColumn({name: "entity", label: "Name"}),
                            search.createColumn({name: "memo", label: "Memo"}),
                            search.createColumn({name: "amount", label: "Amount"}),
                            search.createColumn({name: "duedate", label: "Due Date"}),
                            search.createColumn({
                                name: "custentity_jj_test_email",
                                join: "customer",
                                label: "Email"
                            })
                        ]
                });
                var searchResult = invoiceSearchObj.run().getRange({
                    start: 0,
                    end: 1000
                });

                var split_ap;
                var search_result_array = [];
                log.debug('Before search run')
                searchResult.forEach(function (element) {
                    invoice_Id = element.getValue({name: "internalid"});
                    log.debug('Invoice Id', invoice_Id)
                    ap_address = element.getValue(({
                        name: "custentity_jj_test_email",
                        join: "customer",
                        label: "Email"
                    }))

                    log.debug('Ap adress before', ap_address)
                    
                   split_ap = ap_address.split(',').join(',').split(';').join(',').split(',')
                  
                    log.debug('Split ap',split_ap)
 
                    var emailArray = [];

                    //To check for email validation for the values in the array after splitting by ;
                    for (var j = 0; j < split_ap.length; j++) {
                        var check = (split_ap[j].match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi));
                        log.debug('Check', check)
                        //If there is a value in the variable check, then it is pushed to the emailArray.
                        if (check) {
                            emailArray.push(check[0])
                        }
                    }

                    log.debug('Getemail', emailArray)

                    //Invoice id and array of valid emails are pushed to search_result_array
                    search_result_array.push({
                        invoice_Id: invoice_Id,
                        ap_address: emailArray
                    })


                })
                return search_result_array;
            } catch (e) {
                log.debug('Error @ GetInputData', e)
            }


        }


        const map = (mapContext) => {


        }

        const reduce = (reduceContext) => {

            try {
                
                var map_result = (reduceContext.values);
              
                var mapResult = JSON.parse(map_result[0])
                
                invoice_intid = mapResult.invoice_Id

                //Code is executed only when there is at least one email address in valid format extracted from the field
                if (mapResult.ap_address) {
                    var apLength = mapResult.ap_address.length
                    log.debug('Invoice id reduce', invoice_intid)

                    //Invoice PDF
                    var invoice = render.transaction({
                        entityId: parseInt(invoice_intid),
                        printMode: render.PrintMode.PDF
                    })
                    //send email by attaching invoice pdf created.
                    log.debug('Aplength', apLength)
                    try {
                        for (var j = 0; j < apLength; j++) {
                            log.debug('j', mapResult.ap_address[j])

                            //Sending emails by attaching the invoice pdfs and storing the email sent details to the communication tab in corresponding invoice record.

                              email.send({
                                    author:5272,
                                    recipients: mapResult.ap_address[j],
                                    subject: 'Friendly Reminder of Payment Due',
                                    body: 'Dear Valued Customer,\n \n As a friendly reminder, your payment for the attached invoice will be due in 7 days. Remittance information is at the bottom of the invoice.  If you have any questions, please reach out to our Finance Team at ar@brobinson.com. Thank you for your order and we look forward to your future business.',
                                    attachments: [invoice],
                            	relatedRecords: {
                                      transactionId: parseInt(invoice_intid)
                                  }
                                })
                        }

                    } catch (e) {
                        log.debug('Error@Email Send', e)
                    }
                } else {
                    log.debug('No valid emails')
                }
            } catch (e) {

                log.debug('Error @ reduce', e)
            }


        }

        const summarize = (summaryContext) => {
            try {
                log.debug('InvalidEmailArray summary', summaryContext)
            } catch (e) {
                log.debug('Error@Summarize', e)
            }
        }

        return {getInputData, reduce, summarize}

    });

Leave a comment

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