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
Ak RAk R 

Case reply mails not getting added as case comment. Instead it creates new case.

I need to add replies to a case mail as case comment. The case mail is sent via an apex code and the mail has case threadId in the subject and body of the mail. Even then the replies to that mail is creating new case instead of creating a comment to the parent case.

There is already and email-to-case setup configured with a different sender address.The email template is of visualforce type and the sender address used is an org-wide-email address.
How can this be done?
SwethaSwetha (Salesforce Developers) 
HI Akshay,
Considering that the thread ID is added the subject of the email/ the body to determine what is missing, can you include code snippet that I can use to replicate this behaviour in my org.

Related posts from past: https://help.salesforce.com/s/articleView?id=000330749&type=1
https://salesforce.stackexchange.com/questions/4580/email-reply-to-new-case-comment
https://salesforce.stackexchange.com/questions/248511/email-to-casemultiple-cases-for-same-email-replies

Thanks
Ak RAk R
This is the snippet that sends the mail.

public void sendEmail(Id ContactID, String templateName,string type){
        OrgWideEmailAddress[] owea = [SELECT Id FROM OrgWideEmailAddress WHERE Address = 'xx@xxxx.com'];
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        if (owea.size() > 0) {
          mail.setOrgWideEmailAddressId(owea.get(0).Id);
    }

        mail.setTargetObjectId(ContactID);
        mail.setWhatId(getCaHeader().Case_Number__c);
        mail.setUseSignature(false);

        mail.setTemplateID([SELECT Id FROM EmailTemplate WHERE Name =: templateName LIMIT 1].Id);
        mail.setSaveAsActivity(true);
        if(Test.isRunningTest() == false)
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }