I have implemented a functionlity in apex which on click of button sends email to contacts of specific case id.
I want is that the email being sent should get stored in email related list of that case id.
Could you please let me know how i can achieve that?
My apex code for sending email is below :
//get the last inserted attachment
Attachment attach = [SELECT Body,ContentType,Name FROM Attachment where parentId = :caseid ORDER BY CreatedDate DESC LIMIT 1];
Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
If(attach != null){
efa.setFileName('file.pdf');
efa.setBody(attach.body);
efa.setContentType(attach.ContentType);
}
//list for sending multiple message at once
list<Messaging.SingleEmailMessage> lstemail = new list<Messaging.SingleEmailMessage>();
//draft email to send to secondary contact
Messaging.SingleEmailMessage mailHandler = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {objContact.RMA_Secondary_Contact_Email__c};
mailHandler.setToAddresses(toAddresses);
mailHandler.setSubject('RMA Form');
mailHandler.setPlaintextbody('Hello ' + objContact.RMA_Secondary_Contact_First_Name__c+'\n\n Please Find the pdf attached\n\nRegards\nXyz');
System.debug('messagetext' +mailhandler);
mailHandler.setFileAttachments(new Messaging.EmailFileAttachment[] { efa });
//add email to list
lstemail.add(mailHandler);
//draft email to send to primary contact
Messaging.SingleEmailMessage mailHandler1 = new Messaging.SingleEmailMessage();
String[] toAddresses1 = new String[] {objContact.Contact.Email};
mailHandler1.setToAddresses(toAddresses1);
mailHandler1.setSubject('RMA Form');
mailHandler1.setPlaintextbody('Hello ' + objContact.Contact.Name+'\n\n Please Find the pdf attached\n\nRegards\nXyz');
System.debug('messagetext' +mailhandler1);
mailHandler1.setFileAttachments(new Messaging.EmailFileAttachment[] { efa });
//add email to list
lstemail.add(mailHandler1);
//send all the email in list and get the result
Messaging.sendEmailResult[] r= Messaging.sendEmail(lstemail);