[SalesForce] Email body is showing empty for some emails in email service handler

I have developed an email service handler in which I am noticing some some of them showing null in the plainTextBody field although there is a body present. Below is my sample code

global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
    Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();

    try{            
       System.debug('from email address = '+email.fromAddress);
        System.debug('email subject = '+email.subject);
        System.debug('plainTextBody = '+email.plainTextBody); //this is showing blank in logs

The forwarding inbox has a copy of the email forwarded to the email handler address and I see the body is present in the email. Initially I thought it was due to HTML content in the email but I tried a couple of emails with HTML content and they seem to show the body fine(with html markup as text).

Could it be because the email was encrypted by the sender?

Best Answer

This code works if plainTextBody is blank, but htmlBody is not. There is a regex express to strip all html tags from the html body. The result may not be pretty, but the text should survive.

        String plainText = '';
    if (string.isNotBlank(email.plainTextBody)) {
        try {
              plainText = email.plainTextBody.substring(0, email.plainTextBody.indexOf('<stop>'));
        }
        catch (System.StringException e) {
             plainText = email.plainTextBody;
        }          
    } 
    else if (string.isNotBlank(email.htmlBody)) {
            // Process html body only if plain text body is blank      
        try {
            plainText = email.htmlBody.substring(0, email.htmlBody.indexOf('<stop>'));
        }
        catch (System.StringException e) {
             plainText = email.htmlBody;
        }
            // Strip all html tags from html body
        Pattern htmlPattern = Pattern.compile('</?[a-z][a-z0-9]*[^<>]*>'); 
        plainText = htmlPattern.matcher(plainText).replaceAll('');                     
    }
Related Topic