Click here to Skip to main content
15,915,763 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to read emails through java code and performing operations. but i am unable to perform operation on no subject emails . Also unable to find emails with no subject.

Message message = messages[i];
String subject=message.getSubject().toString();
what should i check for no subject emails?

What I have tried:

Message message = messages[i];
String subject=message.getSubject().toString();
Posted
Updated 19-Mar-18 4:54am

1 solution

While the subject is not a required header field, nearly all mails will have one. If you need a mail without a subject header, just create one (e.g. by sending it to the address that is used as input for your application). But it might be necessary to create/send the mail programmatically instead of using an email client application because those have an input field for the subject and might therefore always include the header even with empty content.

How to detect a mail without subject depends on the implementation of the Message.getSubject() function. It may return an empty string, a null pointer, or throw a MessagingException (I have not found a clear statement in the documentation but you should be able to find out when processing a mail without the subject header).

In the first case you can't detect mails without subject (you can only detect empty subject fields). In the third case you have to catch the exception.

A code snippet handling all cases:
Java
try {
    String subject=message.getSubject();
    if (subject == null)
    {
        // no subject (if null is returned for this case)
    }
    else if (subject.isEmpty())
    {
        // empty subject
    }
} catch (MessagingException me) {
    // Handle exception here
    // Invalid message or - if it applies - subject not present
}

Finally there is no need to call toString() because Message.getSubject() returns a string.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900