用javamail顯示復合郵件的內容(2) - 中國WEB開發者網絡 (http://www.webasp.net) -- 技術教程 (http://www.webasp.net/article/) --- 用javamail顯示復合郵件的內容(2) (http://www.webasp.net/article/18/17341.htm) |
| -- 作者:未知 -- 發佈日期: 2005-04-06 |
| 那沒如何得到part得內容呢?
這裡有一點要強調,並非得到part對像後,調用part.getContent()就能得到part的內容。當初我就是在這裡被卡住了。為什麼呢?原因是: 理論上的指明內容第一個part,既不是一個text/plain類型,也不是一個text/html類型。所以,第15行是永遠不成立的。後來經過研究發現,指明內容的第一個part又是一個multipart類型。也就是說,這個郵件可分為多個部分,正文和圖片等,而正文部分又可以分為多個部分,如plain的正文和html的正文。這樣,就像一個樹。只有到達葉子時,你才能知道它時plain還是html。因此,我們在part中遞歸調用本身就解決了問題。 1 public String getPart(Part part, int partNum) 2 throws MessagingException,IOException 3 { 4 String s=""; 5 String s1=""; 6 String s2=""; 7 String s3=""; 8 String sct = part.getContentType(); 9 if (sct == null) 10 { 11 s="part 無效"; 12 return s; 13 } 14 ContentType ct = new ContentType(sct); 15 if (ct.match("text/plain")) 16 { 17 // display text/plain inline 18 s1=" "+(String)part.getContent()+" "; 19 } 20 else 21 { 22 String temp=""; 23 if ((temp = part.getFileName()) != null) 24 s2= "Filename: " + temp + " "; 25 temp = null; 26 if ((temp = part.getDescription()) != null) 27 s3= "Description: " + temp + " "; 28 } 29 s=s1+s2+s3; 30 return s; 31 } 下面是經過改造的getpart方法(很粗糟,未優化),使用它能夠正確顯示復合郵件。 public String getPart(Part part, int partNum, int msgNum,int x) throws MessagingException,IOException { String s=""; String s1=""; x參數來確定是以html格式顯示還是以plain String s2=""; String s3=""; String s5=""; String sct = part.getContentType(); if (sct == null) { s="part 無效"; return s; } ContentType ct = new ContentType(sct); if (ct.match("text/html")||ct.match("text/plain")) { // display text/plain inline s1=" "+(String)part.getContent()+" "; } else if(partNum!=0) { String temp=""; if ((temp = part.getFileName()) != null) { s2= "Filename: " + temp + " "; } /* out.println(" HttpUtils.getRequestURL(req) + "?message=" + msgNum + "&part=" + partNum + "">Display Attachment"); */ } |
| webasp.net |