+ Start a Discussion
deplaideplai 

capturing emails into comments

We have a need to capture all emails into comments so that when a customer logs in to their portal, all the information is in the same section.  We are trying not to purchase email2case premium, which I know will do the trick.  We have coded our own trigger to do this, but the problem is it captures the whole email.  I'm not quite sure how to code it to capture only the new text from the email and not all the subsequent replies.

trigger AfterEmailMessage on EmailMessage bulk (after insert) {
  List <CaseComment> commentsToInsert = new List <CaseComment>();
  Map <String,Case> cases = new Map<String,Case>();
  List<String> casesIds = new List<String>();
  
  public final Id recordTypeId = [Select id from RecordType where name =: 'Internal'].id;
  
  for (EmailMessage em : Trigger.new){
    casesIds.add(em.parentId);
  }
  
  for(Case c : [Select id,RecordTypeId from Case where id in :casesIds]){
    cases.put(c.id,c);
  }
  
  for (EmailMessage em : Trigger.new){
    if (cases.get(em.parentId).recordTypeId == recordTypeId){
      CaseComment cc = new CaseComment();
      cc.CommentBody = em.TextBody;
      cc.IsPublished = true;
      cc.ParentId = em.parentId;
      commentsToInsert.add(cc);
    }
  }
  
  insert commentsToInsert;
  
}

 Any suggestions would be greatly appreciated.  Thanks.

LVSLVS

This is a very late reply, but it's an interesting question.

 

Were you able to solve this? I'd recommend you do some research on how email clients parse email and differentiate old email from new. I'm pretty sure from my rare experience with email parsing that there are some standard delimiters that you can depend on - however am not able to remember any!

 

Good luck with your research!

 

~LVS