0

I built an apex email service setup to receive email communications on our Lead and Opportunities, and very quickly I started receiving a lot of "Undeliverable" errors due to the email body size.

After closer inspection, I saw that the emails that failed most often had a very very big chunk of metadata and CSS code on the htmlBody inside the <head> tag, along with a lot of conditional tags for IE like <!--[if (gte mso 9)|(IE)]>, complicated tables and a lot of extra unneeded whitespaces.

Unfortunately, I can't just truncate the email body, as that means we'd have just half the email (since most of the email size is at the start, on the <head> tag), and that doesn't really work for the stakeholders. Similarly, cutting down the text from the thread's previous emails, isn't welcomed either by them. Therefore, I came up with an ugly regex + string.split solution that has been mostly working.

However, the regex block tasked with removing the conditional tags, quite often generates error emails with the following message:

Salesforce System Error: 549768602-22860 (875220174) (875220174)

Therefore, I wonder whether I can solve this without resorting to regex, or if there's any alternative approach to solve this issue?

I'm aware regex is not an appropriate tool to process HTML, but since each email is different, I can't just hardcode some snipping based on arbitrary line numbers / character positions, so I couldn't come up with anything better.

This is the code that I'm using currently on the apex email service class:

private static final Integer EMAIL_SUBSTRING_SIZE = 5000;
emailMessage.HtmlBody = email.htmlBody == null ? null : cleanHtml(email.htmlBody).left(32000);
emailMessage.TextBody = email.plainTextBody == null ? null : email.plainTextBody.left(32000);
public static String cleanHtml(String input) {
    String output = input;

    /* Don't use this for now as the System.UnexpectedException is not handleable.
        Looks like the issue has to do with HTML, so will need to put some time into sanitzing it first.
    try {
        String commentsRegexp = '<!--(?:.|\\n|\\r|\\s)+?-->';
        output = output.replaceAll(commentsRegexp, '');
    } catch(exception e) {
        // Sometimes this triggers an internal SF error for no apparent reason:
        // Salesforce System Error: 549768602-22860 (875220174) (875220174)
        // Sad but life goes on
    }
    */

    // Remove <head> tag and all it includes
    try {
        if (output.contains('<head>') && output.contains('</head>')) {
            List<String> firstSplit = output.split('<head>');
            List<String> secondSplit = firstSplit[1].split('</head>');
            output = firstSplit[0]+secondSplit[1];
        }
    } catch(exception e) {
        // Again just in case
    }

    // Remove unneeded whitespaces and linejumps
    try {
        // Substring into blocks of n characters to avoid having "regex too complicated" error.
        Integer substringsAmount = Integer.valueOf(output.length()/EMAIL_SUBSTRING_SIZE);
        List<String> outputSubstrings = new List<String>();
        for (Integer i = 0; i < substringsAmount; i++) {
            String substringInput = output.substring(i*EMAIL_SUBSTRING_SIZE, (i+1)*EMAIL_SUBSTRING_SIZE);
            outputSubstrings.add(removeExtraNewlinesAndTrim(substringInput));
        }
        outputSubstrings.add(removeExtraNewlinesAndTrim(output.substring(substringsAmount*EMAIL_SUBSTRING_SIZE)));
        output = String.join(outputSubstrings, '');
    } catch(exception e) {
        // And yet again
    }

    return output;
}
public static String removeExtraNewlinesAndTrim(String input) {
    List<String> emailLines = new List<String>();
    for (String emailLine : input.split('\n')) {
        emailLine = emailLine.trim();
        if (!String.isEmpty(emailLine)) {
            emailLines.add(emailLine);
        }
    }
    return String.join(emailLines, '\n');
}

Thanks beforehand!

0

You must log in to answer this question.