Link to home
Start Free TrialLog in
Avatar of askJava2
askJava2

asked on

getContent Error

Hi
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 java.io.InputStreamReader.<init>(InputStreamReader.java:82)
        at com.sun.mail.handlers.text_plain.getContent(text_plain.java:65)
        at javax.activation.DataSourceDataContentHandler.getContent(DataHandler.java:745)
        at javax.activation.DataHandler.getContent(DataHandler.java:501)
        at javax.mail.internet.MimeMessage.getContent(MimeMessage.java:1259)
        at RecvEmail.printMessage(RecvEmail.java:137)
        at RecvEmail.main(RecvEmail.java:81)
java.lang.NullPointerException: charsetName
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of askJava2
askJava2

ASKER

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) {
                        ...
                        }

Are you sure that the message is not a non-text attachment?
see: http://java.sun.com/developer/onlineTraining/JavaMail/contents.html (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, ...
  }
...
}
>        if (cnt instanceof Multipart) {

You certainly should be checking what type the parts are, what does your code currently look like?
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
}
Heres an example for reading messages and their attachments

import java.io.*;
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");
    folder.open(Folder.READ_ONLY);

    BufferedReader reader = new BufferedReader (
      new InputStreamReader(System.in));

    // 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());

      System.out.println(
        "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) {
          handleMultipart((Multipart)content);
        } else {
          handlePart(message[i]);
        }
      } else if ("QUIT".equals(line)) {
        break;
      }
    }

    // Close connection
    folder.close(false);
    store.close();
  }
  public static void handleMultipart(Multipart multipart)
      throws MessagingException, IOException {
    for (int i=0, n=multipart.getCount(); i<n; i++) {
      handlePart(multipart.getBodyPart(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) && 
          (contentType.toLowerCase().substring(
           0, 10).equals("text/plain"))) {
        part.writeTo(System.out);
      } else { // Don't think this will happen
        System.out.println("Other body: " + contentType);
        part.writeTo(System.out);
      }
    } 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 = bis.read()) != -1) {
      bos.write(aByte);
    }
    bos.flush();
    bos.close();
    bis.close();
  }
}