Although javamail APIs are completely encapsulated, there are still a lot of logic and details to process to write a program that correctly displays complex emails. Below is the servlet I recently compiled when I made a webmail. Basically, I can correctly read text, HTML, and HTML to display images and attachments. This servlet also deals with common Chinese problems, including themes, attachments, HTML pictures, and email addresses. In general, there are two difficulties: 1. When attachments and web images are captured, you need to locate the nodeid of a number of nodes. partid alone cannot be used; 2. the encoding of base64 is inconsistent with that of the client server in Chinese. In this program, three displaypart () methods are implemented, which are more efficient in combination with different situations. Another unhandled part of this program is that I can calculate a maximum of 10 nodeids. If you have other questions, please let me know. I am here to give a reference example for later beginners to avoid detours.
Import java. Io. ioexception;
Import java. Io. inputstream;
Import java. Io. unsupportedencodingexception;
Import java. util. hashmap;
Import javax. Mail. folder;
Import javax. Mail. message;
Import javax. Mail. messagingexception;
Import javax. Mail. multipart;
Import javax. Mail. part;
Import javax. Mail. store;
Import javax. Mail. Internet. internetaddress;
Import javax. Mail. Internet. mimeutility;
Import javax. servlet. servletexception;
Import javax. servlet. servletoutputstream;
Import javax. servlet. http. httpservletrequest;
Import javax. servlet. http. httpservletresponse;
Import javax. servlet. http. httpsession;
Import chunwei. Mail. login;
Import chunwei. Mail. mailuserdata;
/**
* Servlet implementation class for servlet: mailservlet
* Author: luchunwei Email: luchunwei@gmail.com
*/
Public class mailnode extends javax. servlet. http. httpservlet implements javax. servlet. servlet {
Private Static final long serialversionuid = 1l;
Protected void doget (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
Nodeid = "";
Node = "0 ";
Currentnodeid = 0;
Url = request. getrequesturl (). tostring ();
Httpsession ses = request. getsession ();
Mailuserdata mud = (mailuserdata) SES. getattribute ("mud ");
Servletoutputstream out = response. getoutputstream ();
Response. setcontenttype ("text/html; charset = gb2312 ");
Int msgid =-1, partid =-1;
String partname = NULL;
String nodepara = NULL;
If (request. getparameter ("msgid ")! = NULL)
Msgid = integer. parseint (request. getparameter ("msgid "));
Msgidstr = "msgid =" + msgid;
If (request. getparameter ("partid ")! = NULL)
Partid = integer. parseint (request. getparameter ("partid "));
If (request. getparameter ("partname ")! = NULL)
Partname = new string (request. getparameter ("partname"). getbytes ("ISO-8859-1"), "gb2312 ");
If (request. getparameter ("Node ")! = NULL)
Nodepara = request. getparameter ("Node ");
System. Out. println (nodepara );
// System. Out. println (msgid + ":" + partid + ":" + partname );
If (partname! = NULL ){
// Displayimages
Try {
Displaypart (partname, response, out );
} Catch (messagingexception e ){
E. printstacktrace ();
} Catch (ioexception e ){
E. printstacktrace ();
}
Return;
}
//--------------------------
If (mud = NULL ){
Login Login = New Login ("IMAP", "mail.server.com",-1, "user", "password ");
Login. login ();
If (login. getresult () = 1 ){
Httpsession session = request. getsession ();
Session. setmaxinactiveinterval (3600 );
Session. setattribute ("mud", login. getmud ());
}
Mud = (mailuserdata) SES. getattribute ("mud ");
}
//---------------------------
If (mud = NULL ){
Out. Print ("<error> login first (no session) </error> ");
} Else {
// Folder = mud. getfolder ();
Try {
//------------------------
Store store = mud. getstore ();
Folder folder = store. getfolder ("inbox ");
Folder. Open (Folder. read_only );
//------------------------
Message M = folder. getmessage (msgid );
// If (partid =-1 ){
If (nodepara = NULL ){
// If (! IMGs. isempty () IMGs. Clear ();
Messagehtml = "";
Attachment = "";
Recipients = getallgetrecipients (m );
Out. Print (displaymessage (request, M, partid ));
} Else {
Displaypart (M, nodepara, response, out );
}
} Catch (messagingexception e ){
E. printstacktrace ();
} Catch (ioexception e ){
E. printstacktrace ();
} Catch (exception e ){
E. printstacktrace ();
}
}
}
Protected void dopost (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
Doget (request, response );
}
String stdurl = "";
String url = "";
String msgidstr = "";
String messagehtml = "";
String attachment = "";
String recipients = "";
String nodeid = "";
Int currentnodeid = 0;
String node = "";
Hashmap <string, part> IMGs = new hashmap <string, part> ();
Public String displaymessage (httpservletrequest request, Part p, int partid) throws exception {
// System. Out. println ("type:" + P. getcontenttype ());
If (currentnodeid = 1 &&! Node. endswith ("0 ")){
Nodeid = nodeid. substring (0, (nodeid. Length ()-2 ));
}
Node = nodeid + currentnodeid;
System. Out. println (node );
If (P. ismimetype ("multipart /*")){
Nodeid + = currentnodeid + "-";
Multipart MP = (multipart) p. getcontent ();
Int CNT = mp. getcount ();
String mpct = mp. getcontenttype (). tolowercase ();
For (INT I = 0;
I <CNT;
I ++ ){
If (mpct. startswith ("multipart/alternative") & MP. getbodypart (I). getcontenttype (). tolowercase (). startswith ("text/plain") continue;
Currentnodeid = I;
Displaymessage (request, MP. getbodypart (I), I );
}
}
If (P. ismimetype ("text/plain") | P. ismimetype ("text/html ")){
If (messagehtml = ""){
Messagehtml = (string) p. getcontent ();
// System. Out. println (messagehtml );
} Else {
Messagehtml = messagehtml + "<HR/>" + (string) p. getcontent ();
// System. Out. println (messagehtml );
}
} Else if (P. ismimetype ("message/rfc822 ")){
// Nested message
// Displaymessage (request, (Part) p. getcontent (), partid );
} Else {
If (node. Length ()> 2) node = node. substring (2 );
System. Out. println (node );
String disposition = P. getdisposition ();
// System. Out. println ("Disposition:" + disposition );
If (Disposition! = NULL & disposition. equalsignorecase (part. Attachment )){
String filename = getfilename (P );
// IMGs. Put (filename, P );
// Put all attachment into the memory, which will cause memory expansion. If it is cleared in time, the page back will not be accessible to attachment.
// Attachment + = "," + "<a href = '" + URL + "/" + filename + "? "+ Msgidstr +" & partid = "+ partid +" '> "+ filename +" </a> ";
Attachment + = "," + "<a href = '" + URL + "/" + filename + "? "+ Msgidstr +" & node = "+ node +" '> "+ filename +" </a> ";
// Attachment + = "," + "<a href = '" + URL + "/" + filename + "? "+" & Partname = "+ getfilename (p) +" '> "+ filename +" </a> ";
// System. Out. println (Attachment );
} Else {
// If (Disposition! = NULL & disposition. equalsignorecase (part. inline )){
If (getcid (p )! = NULL ){
// System. Out. println ("Enter Replace ");
IMGs. Put (getfilename (P), P );
// String uri = URL + "? "+ Msgidstr +" & partid = "+ partid;
String uri = URL + "? "+ Msgidstr +" & node = "+ node;
// String uri = URL + "? "+" & Partname = "+ getfilename (P );
String T = messagehtml. substring (messagehtml. indexof (getcid (p)-1 );
If (! (T. startswith ("/" ") | T. startswith ("/'"))){
Uri = "'" + URI + "'";
}
Messagehtml = messagehtml. Replace (getcid (P), Uri );
// System. Out. println ("CID:" + getcid (p ));
// System. Out. println (URI );
}
}
}
Return messagehtml + "attachhncwx =" + attachment + recipients;
}
Public void displaypart (message m, string node, httpservletresponse response, servletoutputstream out)
Throws messagingexception, ioexception {
Part = getpart (M, node );
String SCT = part. getcontenttype ();
Response. setcontenttype (SCT );
Output (part, out );
}
Private part getpart (Part M, string nodes) throws numberformatexception, messagingexception, ioexception {
If (node = NULL) return m;
String node = nodes. substring (0, 1 );
System. Out. println (nodes + ":" + node );
Int nid = integer. parseint (node );
If (M. getcontent () = NULL) system. Out. Print ("NO content ");
Part p = (multipart) M. getcontent (). getbodypart (NID );
If (nodes. Length ()> 2) nodes = nodes. substring (2 );
Else {
If (nodes. Length () = 1) nodes = "";
}
If (nodes. Length ()> 0) P = getpart (p, nodes );
Return P;
}
Public void displaypart (string partname, httpservletresponse response, servletoutputstream out) throws messagingexception, ioexception {
// System. Out. println (IMGs. keyset () + ":" + partname );
Part = IMGs. Get (partname );
String Ct = part. getcontenttype ();
If (CT! = NULL) response. setcontenttype (CT );
// ===== Start push stream into out
Inputstream in = part. getinputstream ();
Bytearrayoutputstream Bos = new bytearrayoutputstream ();
Byte [] buffer = new byte [8192];
Int COUNT = 0;
While (COUNT = in. Read (buffer)> = 0) Bos. Write (buffer, 0, count );
In. Close ();
Try {
Out. Write (Bos. tobytearray ());
Out. Flush ();
} Catch (exception e ){
}
Out. Close ();
// ===== End
}
Public void displaypart (message m, int partid, httpservletresponse response, servletoutputstream out) throws messagingexception, ioexception {
Multipart MP = (multipart) M. getcontent ();
Part = mp. getbodypart (partid );
String SCT = part. getcontenttype ();
// Contenttype Ct = new contenttype (SCT );
Response. setcontenttype (SCT );
If (SCT = NULL ){
Out. println ("invalid part ");
Return;
}
// ===== Start push stream into out
Inputstream in = part. getinputstream ();
Bytearrayoutputstream Bos = new bytearrayoutputstream ();
Byte [] buffer = new byte [8192];
Int COUNT = 0;
While (COUNT = in. Read (buffer)> = 0) Bos. Write (buffer, 0, count );
In. Close ();
Try {
Out. Write (Bos. tobytearray ());
Out. Flush ();
} Catch (exception e ){
}
Out. Close ();
// ===== End
}
Private string getfilename (Part p) throws messagingexception, unsupportedencodingexception {
// System. Out. println ("filename :");
String filename = P. getfilename ();
If (filename = NULL) return NULL;
Filename = new string (filename. getbytes ("ISO-8859-1"), "gb2312 ");
Int indexstart = filename. touppercase (). indexof ("=? GB ");
If (indexstart>-1 ){
Filename = filename. substring (0, indexstart) + mimeutility. decodetext (filename. substring (indexstart ));
}
Return filename;
}
Private string getcid (Part p) throws messagingexception {
String cidraw = NULL, cid = NULL;
String [] headers = P. getheader ("content-ID ");
If (headers! = NULL & headers. length> 0 ){
Cidraw = headers [0];
} Else {
Return NULL;
}
If (cidraw. startswith ("<") & cidraw. endswith ("> ")){
Cid = "CID:" + cidraw. substring (1, cidraw. Length ()-1 );
} Else {
Cid = "CID:" + cidraw;
}
Return CID;
}
/**
* Obtain the recipient, CC, and BCC address and name of the email, according to different parameters passed, "to" ---- recipient "cc" --- CC address "BCC" --- BCC address
* @ Throws exception
*/
Private string getallgetrecipients (message m) throws exception {
Return "mailaddrto =" + getrecipients (M, "")
+ "Mailaddrcc =" + getrecipients (M, "cc ")
+ "Mailaddrbcc =" + getrecipients (M, "BCC ");
}
Private string getrecipients (message m, string type) throws exception {
Stringbuffer mailaddr = new stringbuffer ("");
String addtype = type. touppercase ();
Internetaddress [] address = NULL;
If (addtype. Equals ("")){
Address = (internetaddress []) M. getrecipients (message. recipienttype. );
} Else if (addtype. Equals ("cc ")){
Address = (internetaddress []) M. getrecipients (message. recipienttype. CC );
} Else {
Address = (internetaddress []) M. getrecipients (message. recipienttype. BCC );
}
If (address! = NULL ){
For (INT I = 0;
I <address. length;
I ++ ){
String email = Address [I]. getaddress ();
If (email = NULL)
Email = "";
Else {
Email = mimeutility. decodetext (email );
}
String personal = Address [I]. getpersonal ();
If (Personal = NULL)
Personal = "";
Else {
Personal = mimeutility. decodetext (personal );
}
Mailaddr. append ("/" "+ personal + "/"");
Mailaddr. append ("<");
Mailaddr. append (email );
Mailaddr. append ("> ");
Mailaddr. append (",");
}
}
If (mailaddr. Length ()> 0) mailaddr. deletecharat (mailaddr. Length ()-1 );
Return mailaddr. tostring ();
}
Private void output (Part part, servletoutputstream out) throws ioexception, messagingexception {
// ===== Start push stream into out
Inputstream in = part. getinputstream ();
Bytearrayoutputstream Bos = new bytearrayoutputstream ();
Byte [] buffer = new byte [8192];
Int COUNT = 0;
While (COUNT = in. Read (buffer)> = 0) Bos. Write (buffer, 0, count );
In. Close ();
Try {
Out. Write (Bos. tobytearray ());
Out. Flush ();
} Catch (exception e ){
}
Out. Close ();
// ===== End
}
}