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:
try {
String subject=message.getSubject();
if (subject == null)
{
}
else if (subject.isEmpty())
{
}
} catch (MessagingException me) {
}
Finally there is no need to call
toString()
because
Message.getSubject()
returns a string.