1

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);
1
  • Can someone help..An approach will also be good help for me as i am new to salesforce Jun 24, 2015 at 7:07

2 Answers 2

3

Add the following line to your code. This email will be shown in activity history.

mailHandler.setSaveAsActivity(true); //add mail to the activity history

Update 6/25/2015

2nd Update 6/26/2016

Here is a working solution. There is no tag available to directly assign email to a case. What you can do, create a EmailMessage copy all details from your SingleEmailMessage to this and attach to the case. And you can see it in the email related list.

Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setUseSignature(false);
email.setSaveAsActivity(true);
email.setSubject('Email using Apex');
String[] toAddresses = new String[] {'[email protected]'};
email.setToAddresses(toAddresses);
email.setHtmlBody('<html><body>Hi <b>Saroj</b></body></html>');
Messaging.SingleEmailMessage[] emailList = new Messaging.SingleEmailMessage[] {email};
Messaging.sendEmail(emailList);              
System.debug(emailList[0].getToAddresses());
Case case_temp = [SELECT Id FROM Case where Id = 'XXXXXXXX' LIMIT 1]; // I have tried this code with hard coding a case Id
EmailMessage emailMsg = new EmailMessage(); // Created a EmailMessage and copy all details from above.
emailMsg.ToAddress=(emailList[0].getToAddresses())[0];
emailMsg.Subject=emailList[0].getSubject();
emailMsg.HtmlBody=emailList[0].getHtmlBody();
emailMsg.ParentId = case_temp.Id; //Attach with the case
emailMsg.MessageDate = system.now();
emailMsg.Status = '0';
insert emailMsg;
if(emailList[0].attachments!=null){
    Attachment[] attachments=new Attachment[]{};
    Attachment attachment=null;
    for(Integer i=0;i<emailList[0].attachments.size();i++){
        attachment= new Attachment();
        attachment.Name = emailList[0].attachmentNames[i];
        attachment.Body = emailList[0].attachments[i];
        attachment.ParentId = emailMsg.Id; 
        attachments.add(attachment);
    }
    insert attachments;
}
8
  • Thanks.Itried the code still nothing comes under activity history in case .Dont we need to pass case id as well? Jun 24, 2015 at 12:56
  • mailHandler.setWhatId(caseId); mailHandler.setSaveAsActivity(true); add both of these lines as mentioned by @shingo yamazaki in his answer Jun 24, 2015 at 13:51
  • I have used both the lines as mentioned by you , but noting is coming under activity history for that case id Jun 25, 2015 at 5:21
  • @AnkitaSingh Please find the updated working solution.
    – Saroj Bera
    Jun 25, 2015 at 8:39
  • 1
    @AnkitaSingh You have to create a instance of EmailMessage object and copy all details from your SingleEmailMessage object as mentioned in my code.
    – Saroj Bera
    Jun 25, 2015 at 13:26
1

I think you can use setWhatId() method.

    //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 });
    // here!
    mailHandler.setWhatId(caseId);
    mailHandler.setSaveAsActivity(true);  // default is `true`, but just in case

ref. https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_email_outbound_single.htm#apex_Messaging_SingleEmailMessage_setWhatId

And if you send to Contact object, I recommend to use setTargetObjectId instead of setToAddresses.

6
  • I have to use settoaddressess as i am sending email to custom contact email which doesnot have any id.and I just tries with setwhatid , the email doesnot get store to email related list Jun 24, 2015 at 7:26
  • Is your organization enabled with Email-to-Case or On-Demand Email-to-Case? Jun 24, 2015 at 8:13
  • I dont have any idea about Email-to-Case or On-Demand Email-to-Case..Can you please let me know how to check that? Jun 24, 2015 at 10:38
  • Sorry I'm wrong. setWhatId must be used with setTargetObjectId. You can't store the email sent with setToAddresses, because, I think, you can only choose "To" address from Contact in GUI (Activity History > Send an Email) Jun 25, 2015 at 1:38
  • @shingoYamazaki - Could you please suggest any other workaroung to achieve such functionality? Jun 25, 2015 at 5:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .