Skip to content

Instantly share code, notes, and snippets.

@jeanbaptistebeck
Created October 26, 2023 06:49
Show Gist options
  • Save jeanbaptistebeck/d6533a59def36409a4534e812c9fc8fe to your computer and use it in GitHub Desktop.
Save jeanbaptistebeck/d6533a59def36409a4534e812c9fc8fe to your computer and use it in GitHub Desktop.
public class EmailToCaseParser {
public static String parseEmails(String emailHeaders) {
Pattern p = Pattern.compile('Reply-To: \\s*([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,})');
Matcher pm = p.matcher(emailHeaders);
string res = '';
if (pm.find()) {
res = pm.group(0).replaceAll('Reply-To: ','');
}
return res;
}
}
trigger PopulateCaseWithReplyTo on EmailMessage (after insert) {
for (EmailMessage emailMessage : Trigger.new) {
if (String.isNotBlank(emailMessage.ParentId)){
// EmailToCase : Case record created then EmailMessage record created
String suppliedEmail = [SELECT SuppliedEmail FROM Case WHERE id = :emailMessage.ParentId LIMIT 1].SuppliedEmail; //Get the suppliedEmail From Case to edit it
if (suppliedEmail.equalsIgnoreCase('[email protected]')){ //Only from Helpkit's email
Case caseToUpdate = [SELECT Id, SuppliedEmail FROM Case WHERE id = :emailMessage.ParentId LIMIT 1]; //Get the case to update
String email = EmailToCaseParser.parseEmails(emailMessage.headers); // Get the value for the key Reply-To
caseToUpdate.SuppliedEmail = email;
try {
update caseToUpdate; //Update the Case record which has been saved before the mail
} catch(DmlException e) {
System.debug('An unexpected error has occurred: ' + e.getMessage());
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment