function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

null email.plainTextBody

I have the following code in my email to case class:
global class EmailToCase implements Messaging.InboundEmailHandler {
global Messaging.InboundEmailResult
 handleInboundEmail(Messaging.inboundEmail email,
 Messaging.InboundEnvelope env){
// Create an inboundEmailResult object for returning the result of the Email Service
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
system.debug('\n\nTo: ' + email.toaddresses[0] + '\nFrom: ' + email.fromaddress + '\nSubject: ' + email.subject + '\nBody: ' + email.plainTextBody + '\n');
// remove confidentiality notices from email body
if (email.plainTextBody.contains('CONFIDENTIALITY NOTICE:')) {
    i = email.plainTextBody.indexOf('CONFIDENTIALITY NOTICE:');
    email.plainTextBody = email.plainTextBody.substring(0,i-1);
and this afternoon I have started to get this error in my debug log:
Subject: xxxxxxxx
Body: null

System.NullPointerException: Attempt to de-reference a null object
Class.EmailToCase.handleInboundEmail: line 22, column 5
Line 22, column 5 is trying to reference email.plainTextBody for the first time (.contains).  This has been working for a few weeks.  Has something changed at Salesforce with the inbound email, or do I need to code for some e-mails to actually have a null email.plainTextBody?  The e-mails I received from our mail server do in fact have a body with normal text and a confidentiality notice.  Any ideas?
plainTextBody might be null if the body is actually stored in the htmlBody field...
If the plainTextBody is null, is there any easy way to convert the htmlBody field to text?
Not that easy, I guess it depends on how much HTML there is in the HTML body.  You could probably use a simple regex to filter out all the tags at least.

Matches any HTML tag with any parameters. Very useful to clean HTML of a text

Pattern htmlPattern = Pattern.compile('</?[a-z][a-z0-9]*[^<>]*>'); String contentWithoutHTML= htmlPattern.matcher('<html><body><p>Test 16h37</body></html>').replaceAll(''); System.debug('### Result:'+contentWithoutHTML);