function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Glenn DalyGlenn Daly 

Email Conversation Controller

We have an apex class that in conjunction with a visualforce page is used to send emails to customers from within Salesforce and then store that information as a record.

We need to change one of the fields that pulls through into the email that is sent to the customer. Through Testing I have established the parts of the code that would need changing if the new field was on the same object as the old field. However it's not. It's on a seperate object called BMCServiceDesk__IncidentHistory__c. I'm guessing a new SOQL query would need to be written to query this object and to get the   BMCServiceDesk__note__c field. Below is an extract of the  code, highlighted in bold is what I need removed. I'm guessing the new SOQL query would sit underneath the first query that queries the incident object? Some help on this would be greatly appreciated as I'm very new to this!

public with sharing class COL_JIS_EmailConversationController {
 
        BMCServiceDesk__Incident__c incident = null;
    //List<BMCServiceDesk__CustomAttachment__c> incidentAttachments = null;
    //Map<String,String> incidentAttachments = null;
    
     transient String bodyText = null;
     transient String lastEmailBody = null;
     String subject = null;
    //Attachment attachment = null;
    //String attID = null;
    String toAddresses = '';
    String ccAddresses = '';
    
        public COL_JIS_EmailConversationController(){
      incident =  [select id, name, COL_JIS_Caller_Email__c, COL_JIS_Caller_Name__c, COL_JIS_Subject__c,
                        BMCServiceDesk__openDateTime__c,BMCServiceDesk__IncidentDescription__c,
                        COL_JIS_Service_Desk_Signature__c,COL_JIS_Incident_History_last_entry__c,
                        COL_JIS_Category_Type__c
                               from BMCServiceDesk__Incident__c
                where id = :ApexPages.currentPage().getParameters().get('id') limit 1];
                
            List<BMCServiceDesk__IncidentHistory__c> inboundEmails = [select Id, BMCServiceDesk__note__c, BMCServiceDesk__EmailConversationData__c,
                                                                                    COL_JIS_CCEmailAddresses__c
                                                                                    from BMCServiceDesk__IncidentHistory__c 
                                                                                    where BMCServiceDesk__actionId__c = 'Email Received'
                                                                                    and BMCServiceDesk__FKIncident__c = :ApexPages.currentPage().getParameters().get('id')
                                                                                    order by Name DESC Limit 1]; 
            
            if(inboundEmails != null && inboundEmails.size() > 0){
                lastEmailBody = inboundEmails[0].BMCServiceDesk__note__c;
                if(inboundEmails[0].BMCServiceDesk__EmailConversationData__c != null){toAddresses = inboundEmails[0].BMCServiceDesk__EmailConversationData__c;}
                if(inboundEmails[0].COL_JIS_CCEmailAddresses__c != null){ccAddresses = inboundEmails[0].COL_JIS_CCEmailAddresses__c;}
            }
        if(incident != null){
            toAddresses += incident.COL_JIS_Caller_Email__c;
            subject = incident.COL_JIS_Subject__c;   
        }
        
    }
    
    public PageReference sendEmail() {
        system.debug('enter sendEmail');
        
        // attach files
        attachFile();
        // create a mail incident history record 
        
        BMCServiceDesk__Action__c action = null;
        List<BMCServiceDesk__Action__c> actions = [select Id from BMCServiceDesk__Action__c where BMCServiceDesk__Abbreviation__c = 'EMAILOUT' Limit 1];
        if(actions != null && actions.size()>0){
            system.debug('action found');
          action = actions[0];
        }
        
        String emailBody = bodyText;
        
        
        
        
        system.debug('************************* To: ' + toAddresses);
        COL_JIS_SingleEmailMessage mail = new COL_JIS_SingleEmailMessage();
        
        // get the org address to send the email from
        if(incident.COL_JIS_Category_Type__c != ''){
            List<OrgWideEmailAddress> orgWideAddresses = [SELECT Id, Address FROM OrgWideEmailAddress WHERE DisplayName = :incident.COL_JIS_Category_Type__c limit 1 ];
            if(orgWideAddresses != null && orgWideAddresses.size() > 0){
                mail.setReplyTo(orgWideAddresses[0].Address);
                mail.setOrgWideEmailAddressId(orgWideAddresses[0].Id);
            }
            
        }
        
        // set the from address as the default no reply
        /*List<OrgWideEmailAddress> replyTo = [SELECT Id, Address FROM OrgWideEmailAddress WHERE DisplayName = 'Jisc Remedyforce' limit 1 ];
            if(replyTo != null && replyTo.size() > 0){
                mail.setOrgWideEmailAddressId(replyTo[0].Id);
                
            }*/
        
        mail.setToAddress(toAddresses);
        mail.setSubject(subject + '(Ref:IN:' + incident.Name + ')');
        if(ccAddresses != null && ccAddresses != ''){
            mail.setCcAddresses(ccAddresses);
        }
        mail.setPlainTextBody(buildPlaintextBody());
        mail.setHtmlBody(buildHTMLBody());
        mail.setSaveAsActivity(false);
        Messaging.EmailFileAttachment[] attachArray = new Messaging.EmailFileAttachment[]{};
        String attachmentText = '';
        Integer noOfAttachments = selectedFoos.size();
        
        if(selectedFoos.size() > 0){
            //noOfAttachments ++;
            attachmentText = 'Attachments sent with this email(' + noOfAttachments + ')';
        }
        
        //List<Attachment> attachmentsToInsert = new List<Attachment>();
        Integer i = 1;
        for(Attachment a : selectedFoos){
            
            attachmentText += '\n' + i + '. ' + a.Name;
            i++;
            Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
            Attachment at = [select body from Attachment where Id = :a.Id limit 1];
            attach.setFileName(a.Name);
            attach.setBody(at.body);
            //a.parentId = incident.Id;
            attachArray.add(attach);
            
            //if(a.Id == null){
                //attachmentsToInsert.add(a);
            //}
        }
        //insert attachmentsToInsert;
        
        if(attachmentText != ''){
            attachmentText += '\n***********************';
        }
        mail.setFileAttachments(attachArray);
        
        if(incident != null && action != null){
            system.debug('incident and action exist');
            Integer actionCount = [select count() from BMCServiceDesk__IncidentHistory__c where BMCServiceDesk__FKIncident__c = :incident.Id];
            actionCount++;
            String actionName = incident.Name + '_' + string.valueOf(actionCount);
            // add a note to the incident
            
            emailBody = bodyText + '\n\n' + attachmentText ;
            
            BMCServiceDesk__IncidentHistory__c note = new BMCServiceDesk__IncidentHistory__c(BMCServiceDesk__FKIncident__c = incident.Id,
                                                        BMCServiceDesk__note__c = emailBody,
                                                        BMCServiceDesk__description__c = 'Email sent to ' + toAddresses,
                                                        BMCServiceDesk__FKAction__c = action.Id,
                                                        Name =  actionName,COL_JIS_Caller_Email__c = incident.COL_JIS_Caller_Email__c );
            if(note != null){
                system.debug('insert the note');
                insert note;
            }
        }
            
    try{
        mail.send();
    }catch(Exception e){
        ApexPages.addMessages(e);
        return null;
    }
        
    //return null; // stay on the same page 
    return new PageReference('javascript:window.close()');
}
    
    String[] getAddressArray(String addresses){
        if(addresses == null){addresses = '';}
        String[] addressList = addresses.split(';',0);
        return addressList;
        
    }
    
    public BMCServiceDesk__Incident__c getIncident() {
      
        return incident;
    }
    
    public String getToAddresses() {
        if(toAddresses == null){
            toAddresses = getIncident().COL_JIS_Caller_Email__c;
        }
        return toAddresses;
    }
    
    public void setToAddresses(String s){
        toAddresses = s;
    }
    
    public String getCcAddresses() {
        
        return ccAddresses;
    }
    
    public void setCcAddresses(String s){
        ccAddresses = s;
    }
    
    public String getAdditionalText() {
        return bodyText;
    }

    public void setAdditionalText(String s) {
        bodyText = s;
    }
    
    public String getLastEmailText() {
        
            
        return lastEmailBody;
    }

    public void setLastEmailText(String s) {
        lastEmailBody = s;
    }
    
    public String getSubject() {
        
            
        return subject;
    }

    public void setSubject(String s) {
        subject = s;
    }
    
     public String getAttachFiles() {
        
        String attachmentList = '';
        
        for(Attachment a : attachments){
            attachmentList += a.name + '\n';
        }   
        return attachmentList;
    }

    
    
    // =====================================================================================
    // Private helper methods
    // =====================================================================================
    
    private String buildHTMLBody(){
        // we cannot use templates as this would require a contact or user and would 
        // result in a double count of the email limit.
        
    
        String body = bodyText;
        body = body.replaceAll('\n','<br>');
        body += '<p>Enquiry Number: '  + incident.Name;
        body += '<br>Subject: ';
        if(incident.COL_JIS_Subject__c != null){body += incident.COL_JIS_Subject__c;}
        body += '<br>Open Date: ';
        if(incident.BMCServiceDesk__openDateTime__c != null){body += incident.BMCServiceDesk__openDateTime__c;}
        body += '<br>Caller Name: ';
        if(incident.COL_JIS_Caller_Name__c != null){body += incident.COL_JIS_Caller_Name__c;}
        body += '<br>Enquiry: <p>';
        if(incident.BMCServiceDesk__incidentDescription__c != null){body += incident.BMCServiceDesk__incidentDescription__c.replaceAll('\n', '<br>');}
        body += '<p>Please reply to this email with any updates on this issue.<p>';
        if(incident.COL_JIS_Service_Desk_Signature__c != null){body += incident.COL_JIS_Service_Desk_Signature__c;}
        body += '<p><hr/><p>';
        if(lastEmailBody != null){body += lastEmailBody.replaceAll('\n', '<br>');}
        
        return body;
        
    }
    
    private String buildPlaintextBody(){
        // we cannot use templates as this would require a contact or user and would 
        // result in a double count of the email limit.
        
        String body = bodyText;
        body += '\n\nEnquiry Number: '  + incident.Name;
        body += '\nSubject: ';
        if(incident.COL_JIS_Subject__c != null){body += incident.COL_JIS_Subject__c;}
        body += '\nOpen Date: ';
        if(incident.BMCServiceDesk__openDateTime__c != null){body += incident.BMCServiceDesk__openDateTime__c;}
        body += '\nCaller Name: ';
        if(incident.COL_JIS_Caller_Name__c != null){body += incident.COL_JIS_Caller_Name__c;}
        body += '\nEnquiry: \n';
        if(incident.BMCServiceDesk__incidentDescription__c != null){body += incident.BMCServiceDesk__incidentDescription__c;}
        body += '\nPlease reply to this email with any updates on this issue.\n\n';
        if(incident.COL_JIS_Service_Desk_Signature__c != null){body += incident.COL_JIS_Service_Desk_Signature__c;}
        body += '\n----------------------------------------------------------------\n\n';
        if(lastEmailBody != null){body += lastEmailBody;}

        return body;
        
    }
    
Gabriel McGinnGabriel McGinn

@Glenn Were you able to resolve your issue?

Out of curiosity, how were you populating the field COL_JIS_CCEmailAddresses__c