Skip to content

Instantly share code, notes, and snippets.

@cyberjus
Created August 15, 2014 15:24
Show Gist options
  • Save cyberjus/0bd8c974c6f370e35b77 to your computer and use it in GitHub Desktop.
Save cyberjus/0bd8c974c6f370e35b77 to your computer and use it in GitHub Desktop.
Apex Strip Email Replies Method
/**
* This utility attempts to strip the reply portion of an email by looking for common reply seperators
* The reply separator depends on the email client, so it is not likely to strip all replies 100%
* This is a best effort for known email client formats.
*
* @param String original email message body
* @returns String email message with the reply lines stripped
*/
public static String stripResponse(String email) {
// Normalize line breaks
email.replaceAll('\r\n', '\n');
// Check for On ... wrote: that break to multiple lines and force to one line for filtering
Pattern p = Pattern.compile('(?m)^On .+<[^>]+> wrote:$');
Matcher m = p.matcher(email);
if (m.find()) {
email = email.substring(0,m.start()-1) + email.substring(m.start(), m.end()).replaceAll('\n', '') + email.substring(m.end()+1);
}
String[] lines = email.split('\n');
String out = '';
Boolean firstLine = true;
for (String line : lines) {
// Make sure the reply is not the first line of the message (workaround for Cirrus Insight in particular which starts with From:)
if (!firstLine) {
if (line.equals('--') || line.equals('-- ') ||
line.startsWith('-----Original Message-----') ||
line.startsWith('--------------- Original Message ---------------') ||
line.startsWith('________________________________') ||
(line.startsWith('On ') && line.endsWith(' wrote:')) ||
line.startsWith('From: ') ||
line.startsWith('Sent from my iPhone')) {
break;
}
}
firstLine = false;
out += line + '\n';
}
return out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment