2

我正在使用 JavaMail 在我的 Android 应用程序中阅读邮件。我试图涵盖所有组合,即在自定义服务器/Gmail ID/Live ID 上/从自定义服务器发送/接收的邮件。

从 GMail WITH Attachment 发送的一些邮件会出现问题。我能够接收附件,但内容返回javax.mail.internet.MimeMultipart@44f2e698

这是用于接收和读取消息的代码:

    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imap");

    try {
     /* Create the session and get the store for read the mail. */
     Session session = Session.getInstance(props, null);
     Store store = session.getStore("imaps");
     store.connect("imap.gmail.com", Username, Password);

     /* Mention the folder name which you want to read. */
     Folder inbox = store.getFolder("INBOX");
     System.out.println("No of Unread Messages : " + inbox.getUnreadMessageCount());         

     /* Open the inbox using store. */
     inbox.open(Folder.READ_ONLY);

     Message messages[] = inbox.getMessages();       
     Log.d("Inbox", "Message Count: "+inbox.getMessageCount());

     for (int i = messages.length - 1 ; i > 0; --i) {
         Log.i("ContentType", "ContentType: "+messages[i].getContentType());

         Object msgContent = messages[i].getContent();

         String content = "";

         /* Check if content is pure text/html or in parts */            
         if (msgContent instanceof Multipart) {

             Multipart multipart = (Multipart) msgContent;

             Log.e("BodyPart", "MultiPartCount: "+multipart.getCount());

             for (int j = 0; j < multipart.getCount(); j++) {

              BodyPart bodyPart = multipart.getBodyPart(j);

              String disposition = bodyPart.getDisposition();

              if (disposition != null && (disposition.equalsIgnoreCase("ATTACHMENT"))) { // BodyPart.ATTACHMENT doesn't work for gmail
                  System.out.println("Mail have some attachment");

                  DataHandler handler = bodyPart.getDataHandler();
                  System.out.println("file name : " + handler.getName());                                 
                }
              else { 
                  System.out.println("Content: "+bodyPart.getContent());
                  content= bodyPart.getContent().toString();
                }
            }
         }
         else                
             content= messages[i].getContent().toString();

我对有问题的邮件的了解:

  • getFrom还返回名称,即它采用这种格式 FirstName LastName <emailID@gmail.com>

  • MultiPart 包含 2 个 BodyParts:

    • BodyPart 1 将内容返回为javax.mail.internet.MimeMultipart@44f2e698

    • BodyPart 2 返回正确的附件名称

4

2 回答 2

1

BodyPart 1 将内容返回为 javax.mail.internet.MimeMultipart@44f2e698

尝试在MimeMultiPart上调用 getBodyPart

这可能会返回一个 MimeBodyPart,您可以在 http://docs.oracle.com/javaee/5/api/javax/mail/internet/MimeBodyPart.html#content上调用getContent()

于 2012-10-18T12:52:45.433 回答
0

您可能只处理带有附件的文本消息的最简单情况。MIME 允许更多。您需要了解 multipart/mixed、multipart/alternative、multipart/related 和 multipart/signed 之间的区别。JavaMail FAQ 提供了有关处理附件的更多信息,JavaMail 下载包中包含的 msgshow.java 演示程序展示了如何处理带有嵌套多部分的消息。

于 2012-10-18T16:47:04.337 回答