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
Samantha ChuaSamantha Chua 

Saving Email Sent from Attachment Trigger into Case Activity History

Hi

I have a working code which allows to me to send whatever is being attached to a case. However, although mail.setWhatid(caseId) clearly takes in the case id linked to the attachment being uploaded, the email activity is still not being saved in case activity history. Please advise.
List<Attachment> attList = [SELECT Id, CreatedDate, ParentId, Name, Body, ContentType, Parent.Name FROM ATTACHMENT WHERE Id in: trigger.newMap.keySet()];
    
    for (Attachment a : attList) {
        attachIdList.add(a.parentId);
    }   
    
    List<Case> caseList = [Select Id from Case where Id in: attachIdList LIMIT 1];   
    
    for (Attachment att : attList) {
        for (case c : caseList) {
            if (today.isSameDay(att.CreatedDate) && att.ParentId == c.Id) {
                caseId = att.ParentId;
                aAtt = att;
            }
        }
    }
    
    Messaging.EmailFileAttachment [] efaList = new List<Messaging.EmailFileAttachment> () ;
    Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
    
    efa.setFileName(aAtt.Name);
    efa.setBody(aAtt.Body);
    efa.setContentType(aAtt.ContentType);
    efaList.add(efa) ;   
    
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        
    mail.setSenderDisplayName 'Corporate Sales Support hehehe');
    
    if(efaList != null) {
        mail.setFileAttachments(efaList) ;
    }
    mail.setToAddresses(toAdd);
    mail.setWhatid(caseId);
    //mail.setTemplateId(et.id);
    mail.setPlainTextBody('hellos');
    mail.setUseSignature(false);
    mail.setBccSender(false);
    mail.setSaveAsActivity(true);
    Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});

 
Best Answer chosen by Samantha Chua
Samantha ChuaSamantha Chua
Yupps, positive. Could it be because the trigger is on Attachment but my email is trying to update Case object? and therefore, it ain't working?

All Answers

ClintLeeClintLee
Are you positive the caseId variable is being set?

I'd add a debug statement just before the mail.setWhatId(caseId) line.
 
System.debug('Case Id: ' + caseId);


 
Samantha ChuaSamantha Chua
Yupps, positive. Could it be because the trigger is on Attachment but my email is trying to update Case object? and therefore, it ain't working?
This was selected as the best answer