0

I'm trying to use Contains to judge an email Subject for an Email Service I set up.

Currently, I'm using == , but I want to use Contains because the subject might have characters after the text I'm looking for.

Here is my code :

    global class TerminateInboundEmailHandler implements Messaging.InboundEmailHandler {
    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
        Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
        if ( email.subject == 'Employee Status' ) {
            TerminateController.getInstance().terminate(email.plainTextBody);
        }
        result.success = true;
        return result;
    }
}

How could I work Contains into it ?

2

Use the String.contains() method like so:

global class TerminateInboundEmailHandler implements Messaging.InboundEmailHandler {
    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
        Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
        if ( email.subject != null && email.subject.contains('Employee Status') ) {
            TerminateController.getInstance().terminate(email.plainTextBody);
        }
        result.success = true;
        return result;
    }
}

I also included a null check to avoid the "Attempt to de-reference a null object" exception.

  • 2
    Or possibly containsIgnoreCase if it might not exactly match the case. – sfdcfox Dec 2 '16 at 22:28
  • Thanks Aaron ! One question : Why would it be necessary to put the null check in if it was also doing a Contains check ? If it contains the text in question then it's !=null , right ? ...or maybe I'm missing something ? – Zoom_v Dec 2 '16 at 22:30
  • 1
    Any time you use the dot (.) notation on a variable, it must be instantiated and not null or you will get a "NullPointerException: Attempt to de-reference a null object" exception. The contains method is an instance method which means that it is a child method of your individual String variable. If your string variable is null, it cannot have any child methods, and so you will throw an exception for trying to access children of an class instance that does not exist. – Aaron P. Dec 2 '16 at 22:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.