我開發了簡單的Java應用程序,它讀取我的Gmail收件箱郵件。我可以閱讀電子郵件從和主題。但是,我無法閱讀電子郵件內容。如何閱讀郵件內容?
當我嘗試讀它,我得到以下異常:
Exception Msg: com.sun.mail.imap.IMAPInputStream cannot be cast to javax.mail.Multipart
代碼:
import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPStore;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
public class Read_Mail {
static String from;
public static void main(String args[])
{
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getDefaultInstance(props,null);
IMAPStore imapstore = null;
try
{
imapstore = (IMAPStore) session.getStore("imaps");
imapstore.connect("imap.gmail.com", "usernam[email protected]", "passwordxxx");
final IMAPFolder folder = (IMAPFolder) imapstore.getFolder("Inbox");
folder.open(IMAPFolder.READ_ONLY);
Message[] messages = folder.getMessages();
for (int i = 0; i < messages.length; i++) {
Message message = messages[i];
System.out.println("==============================");
System.out.println("Email #" + (i + 1));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
// System.out.println("Text: " + message.getContent());
Object mp = (Object) message.getContent();
if (mp instanceof String)
{
String body = (String)mp;
System.out.println("MSG Body : " + body);
}
else if (mp instanceof Multipart)
{
Multipart mpp = (Multipart)mp;
final BodyPart bp = mpp.getBodyPart(i);
System.out.println("Text: " +bp.getContent().toString());
} else {
System.out.println("Inside else");
Multipart mpp = (Multipart)mp;
final BodyPart bp = mpp.getBodyPart(i);
System.out.println("Text: " +bp.getContent().toString());
}
}
}
catch(Exception e)
{
System.out.println("Exception Msg: " + e.getMessage());
}
}
}
它總是走了進去else
塊和火災例外。
檢查這個答案下載一個罐子。 http://stackoverflow.com/a/12736366/3907612我認爲你有類似的問題 – Yantraguru
@Kognizant我不認爲鏈接與我的問題 – VVB