getContent Error

Posted on 2005-04-05
Last Modified: 2008-02-07
When i try to read the message content from a pop3 mail box through the getContent() method the following exception occurs. I am rather clueless about it as everything about the mail seems fine. Please note that this error is only for particular mails in the mailbox. Thanks in advance.
java.lang.NullPointerException: charsetName
        at com.sun.mail.handlers.text_plain.getContent(
        at javax.activation.DataSourceDataContentHandler.getContent(
        at javax.activation.DataHandler.getContent(
        at javax.mail.internet.MimeMessage.getContent(
        at RecvEmail.printMessage(
        at RecvEmail.main(
java.lang.NullPointerException: charsetName
Question by:askJava2
    LVL 92

    Accepted Solution

    sounds like a possible malformed message

    have a look at the message source and compare it to one that works

    Author Comment

    I agree but still is there a way to capture the message? I tested the codes and

                      Part mp = message;
                      Object cnt= mp.getContent();

    from here it error out. Usually the type is always "text/plain". So I am thinking if error out, is it possible to capture the message content in the catch (Exception) {
    capture here.

    or is better not to process the message at all?

                      if (cnt instanceof Multipart) {

    LVL 15

    Expert Comment

    Are you sure that the message is not a non-text attachment?
    see: (Getting Attachments)

    String disposition = part.getDisposition();
    if (disposition == null) {
      // Check if plain
      MimeBodyPart mbp = (MimeBodyPart)part;
      if (mbp.isMimeType("text/plain")) {
        // Handle plain
      } else {
        // Special non-attachment cases here of
        // image/gif, text/html, ...
    LVL 92

    Expert Comment

    >        if (cnt instanceof Multipart) {

    You certainly should be checking what type the parts are, what does your code currently look like?
    LVL 15

    Expert Comment

    You can print out the className (for debugging: )  System.out.println(cnt.getClass().getName());

    The code snippet provided above assumes content is MutliPart
    and then you can apply traversal on its content by doing:

    Multipart mp = (Multipart)message.getContent();

    for (int i=0, n=multipart.getCount(); i<n; i++) {
      Part part = multipart.getBodyPart(i));

    ... apply the above logic
    LVL 92

    Expert Comment

    Heres an example for reading messages and their attachments

    import java.util.Properties;
    import javax.mail.*;
    import javax.mail.internet.*;

    public class GetParts {
      public static void main (String args[])
          throws Exception {
        String host = args[0];
        String username = args[1];
        String password = args[2];

        // Get session
        Session session = Session.getInstance(
          new Properties(), null);

        // Get the store
        Store store = session.getStore("pop3");
        store.connect(host, username, password);

        // Get folder
        Folder folder = store.getFolder("INBOX");;

        BufferedReader reader = new BufferedReader (
          new InputStreamReader(;

        // Get directory
        Message message[] = folder.getMessages();
        for (int i=0, n=message.length; i<n; i++) {
           System.out.println(i + ": "
             + message[i].getFrom()[0]
             + "\t" + message[i].getSubject());

            "Do you want to get the content?
               [YES to read/QUIT to end]");
          String line = reader.readLine();
          if ("YES".equals(line)) {
            Object content = message[i].getContent();
            if (content instanceof Multipart) {
            } else {
          } else if ("QUIT".equals(line)) {

        // Close connection
      public static void handleMultipart(Multipart multipart)
          throws MessagingException, IOException {
        for (int i=0, n=multipart.getCount(); i<n; i++) {
      public static void handlePart(Part part)
          throws MessagingException, IOException {
        String disposition = part.getDisposition();
        String contentType = part.getContentType();
        if (disposition == null) { // When just body
          System.out.println("Null: "  + contentType);
          // Check if plain
          if ((contentType.length() >= 10) &&
               0, 10).equals("text/plain"))) {
          } else { // Don't think this will happen
            System.out.println("Other body: " + contentType);
        } else if (disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
          System.out.println("Attachment: " + part.getFileName() +
            " : " + contentType);
          saveFile(part.getFileName(), part.getInputStream());
        } else if (disposition.equalsIgnoreCase(Part.INLINE)) {
          System.out.println("Inline: " +
            part.getFileName() +
            " : " + contentType);
          saveFile(part.getFileName(), part.getInputStream());
        } else {  // Should never happen
          System.out.println("Other: " + disposition);
      public static void saveFile(String filename,
          InputStream input) throws IOException {
        if (filename == null) {
          filename = File.createTempFile("xx", ".out").getName();
        // Do no overwrite existing file
        File file = new File(filename);
        for (int i=0; file.exists(); i++) {
          file = new File(filename+i);
        FileOutputStream fos = new FileOutputStream(file);
        BufferedOutputStream bos = new BufferedOutputStream(fos);

        BufferedInputStream bis = new BufferedInputStream(input);
        int aByte;
        while ((aByte = != -1) {


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Why You Should Analyze Threat Actor TTPs

    After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

    Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
    Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
    Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
    Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…

    779 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    15 Experts available now in Live!

    Get 1:1 Help Now