Search code examples
javastringsmtpcarriage-return

How to check if string contains Carriage Return (CR) or a Line Feed (LF) character in Java


I have a java method which sends email. In the method when I set subject to MimeMessage, I need to check if the subject string contains Carriage Return (CR) or a Line Feed (LF) character.

//Set the From email address
        MimeMessage msg = new MimeMessage(session);
//Set the Email Subject
        msg.setSubject(subject);

I want to validate the subject string if it contains any Carriage Return (CR) or a Line Feed (LF) character as it could be a potential threat.


Solution

  • Try this

    if (subject.contains("\r") || subject.contains("\n")) // then invalid