⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 webmailsession.java

📁 java 开发的一个电子邮局,挺实用的
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
		       ">" are in front of the line, ignoring all whitespaces. */
		    int current_quotelevel=Helper.getQuoteLevel(token);
			

		    /* When we are in a different quote level than the last line, we append all we got
		       so far to the part with the old quotelevel and begin with a clean String buffer */
		    if(current_quotelevel != old_quotelevel) {
			xml_part.addContent(content.toString(),old_quotelevel);
			old_quotelevel = current_quotelevel;
			content=new StringBuffer(1000);
		    }

		    if(user.wantsBreakLines()) {
			Enumeration enum=Helper.breakLine(token,user.getMaxLineLength(),current_quotelevel);
			
			while(enum.hasMoreElements()) {
			    String s=(String)enum.nextElement();
			    if(user.wantsShowFancy()) {
				content.append(Fancyfier.apply(s)).append("\n");
			    } else {
				content.append(s).append("\n");
			    }
			}
		    } else {
			if(user.wantsShowFancy()) {
			    content.append(Fancyfier.apply(token)).append("\n");
			} else {
			    content.append(token).append("\n");
			}
		    }			
		}
		xml_part.addContent(content.toString(),old_quotelevel);		
		// Modified by exce, start
		// Why the following code???
		content=new StringBuffer(1000);
		// Modified by exce, end.
	    } else if(p.getContentType().toUpperCase().startsWith("MULTIPART/ALTERNATIVE")) {
		/* This is a multipart/alternative part. That means that we should pick one of
		   the formats and display it for this part. Our current precedence list is
		   to choose HTML first and then to choose plain text. */
		MimeMultipart m=(MimeMultipart)p.getContent();
		String[] preferred={"TEXT/HTML","TEXT"};
		boolean found=false;
		int alt=0;
		// Walk though our preferred list of encodings. If we have found a fitting part,
		// decode it and replace it for the parent (this is what we really want with an 
		// alternative!)
		// Modified by exce, start
		/**
	    findalt: while(!found && alt < preferred.length) {
		for(int i=0;i<m.getCount();i++) {
		    Part p2=m.getBodyPart(i);
		    if(p2.getContentType().toUpperCase().startsWith(preferred[alt])) {
			parseMIMEContent(p2,parent_part,msgid);
			found=true;
			break findalt;
		    }
		}
		alt++;
	    }
	    **/
		/**
		 * When user try to reply a mail, there may be 3 conditions:
		 * 1. only TEXT exists.
		 * 2. both HTML and TEXT exist.
		 * 3. only HTML exists.
		 *
		 * We have to choose which part should we quote, that is, we must
		 * decide the prority of parts to quote. Since quoting HTML is not
		 * easy and precise (consider a html: <body><div><b>some text..</b>
		 * </div></body>. Even we try to get text node under <body>, we'll
		 * just get nothing, because "some text..." is marked up by
		 * <div><b>. There is no easy way to retrieve text from html 
		 * unless we parse the html to analyse its semantics.
		 * 
		 * Here is our policy for alternative part:
		 * 1. Displays HTML but hides TEXT.
		 * 2. When replying this mail, try to quote TEXT part. If no TEXT
		 *    part exists, quote HTML in best effort(use 
		 *    XMLMessagePart.quoteContent() by Sebastian Schaffert.)
		 */
		while (alt < preferred.length) {
			for(int i=0;i<m.getCount();i++) {
				Part p2=m.getBodyPart(i);
				if(p2.getContentType().toUpperCase().startsWith(preferred[alt])) {
					System.err.println("Processing: " + p2.getContentType());
					parseMIMEContent(p2,parent_part,msgid);
					found=true;
					break;
				}
			}
			/**
			 * If we've selected HTML part from alternative part, the TEXT
			 * part should be hidden from display but keeping in XML for
			 * later quoting operation.
			 *
			 * Of course, this requires some modification on showmessage.xsl.
			 */
			if (found && (alt == 1)) {
			    Node textPartNode = parent_part.getPartElement().getLastChild();
			    NamedNodeMap attributes = textPartNode.getAttributes();
				boolean hit = false;

			    for (int i = 0; i < attributes.getLength(); ++i) {
			    	Node attr = attributes.item(i);
			    	// If type=="TEXT", add a hidden attribute.
			    	if (attr.getNodeName().toUpperCase().equals("TYPE") && 
			    		attr.getNodeValue().toUpperCase().equals("TEXT")) {
			    		((Element)textPartNode).setAttribute("hidden", "true");
			    	}
			    }
			}
			alt++;
	    }
		// Modified by exce, end
		if(!found) {
		    // If we didn't find one of our preferred encodings, choose the first one
		    // simply pass the parent part because replacement is what we really want with
		    // an alternative.
		    parseMIMEContent(m.getBodyPart(0),parent_part,msgid);
		}

	    } else if(p.getContentType().toUpperCase().startsWith("MULTIPART/")) {
		/* This is a standard multipart message. We should recursively walk thorugh all of 
		   the parts and decode them, appending as children to the current part */

		xml_part=parent_part.createPart("multi");

		MimeMultipart m=(MimeMultipart)p.getContent();
		for(int i=0;i<m.getCount();i++) {
		    parseMIMEContent(m.getBodyPart(i),xml_part,msgid);
		}
	    } else {
		/* Else treat the part as a binary part that the user should either download or
		   get displayed immediately in case of an image */
		InputStream in=null;
		String type="";
		if(p.getContentType().toUpperCase().startsWith("IMAGE/JPG") ||
		   p.getContentType().toUpperCase().startsWith("IMAGE/JPEG")) {
		    type="jpg";
		    xml_part=parent_part.createPart("image");
		} else if(p.getContentType().toUpperCase().startsWith("IMAGE/GIF")) {
		    type="gif";
		    xml_part=parent_part.createPart("image");
		} else if(p.getContentType().toUpperCase().startsWith("IMAGE/PNG")) {
		    type="png";
		    xml_part=parent_part.createPart("image");
		} else {
		    xml_part=parent_part.createPart("binary");
		}
		int size=p.getSize();
		if(p instanceof MimeBodyPart) {
		    MimeBodyPart mpb=(MimeBodyPart)p;
 		    System.err.println("MIME Body part (image), Encoding: "+mpb.getEncoding());
		    InputStream is=mpb.getInputStream();
					
		    /* Workaround for Java or Javamail Bug */
		    in=new BufferedInputStream(is);
		    ByteStore ba=ByteStore.getBinaryFromIS(in,size);
		    in=new ByteArrayInputStream(ba.getBytes());
		    /* End of workaround */
		    size=in.available();
					
		} else {
		    System.err.println("*** No MIME Body part!! ***");
		    in=p.getInputStream();
		}
				
		ByteStore data=ByteStore.getBinaryFromIS(in,size);
		if(mime_parts_decoded==null) {
		    mime_parts_decoded=new Hashtable();
		}
		String name=p.getFileName();
		if(name == null || name.equals("")) {
		    name="unknown."+type;
		}
		// Modified by exce, start
		/**
		 * As described in FileAttacher.java line #95 and
		 * SendMessage.java line #390, we use MimeUtility.decodeText() to
		 * decode attachment file name.
		 */
		try {
			name = MimeUtility.decodeText(name);
		} catch (Exception e) {
			System.err.println(e);
		}
		// Modified by exce, end
		// Eliminate space characters. Should do some more things in the future
		name=name.replace(' ','_');
		data.setContentType(p.getContentType());
		data.setContentEncoding("BINARY");
		mime_parts_decoded.put(msgid+"/"+name,data);

		// Modified by exce, start
		/**
		 * For multibytes language system, we have to separate filename into 
		 * 2 format: one for display (UTF-8 encoded), another for encode the
		 * url of hyperlink.
		 * `filename' is for display, while `hrefFileName' is for hyperlink. 
		 * To make use of these two attributes, `showmessage.xsl' is slightly
		 * modified.
		 */
		data.setName(name);
		xml_part.setAttribute("filename",name);
		// Transcode name into UTF-8 bytes then make a new ISO8859_1 string to encode URL.
		xml_part.setAttribute("hrefFileName", URLEncoder.encode(new String(name.getBytes("UTF-8"), "ISO8859_1")));
		// Modified by exce, end
		xml_part.setAttribute("size",size+"");
		String description=p.getDescription()==null?"":p.getDescription();
		xml_part.setAttribute("description",description);
		StringTokenizer tok=new StringTokenizer(p.getContentType(),";");
		xml_part.setAttribute("content-type",tok.nextToken().toLowerCase());
	    }
	} catch(java.io.IOException ex) {
	    ex.printStackTrace();
	} catch(MessagingException ex) {
	    throw ex;
	} catch(Exception ex) {
	    ex.printStackTrace();
	}
    }
    
    public ByteStore getMIMEPart(String msgid,String name) {
	if(mime_parts_decoded != null) {
	    return (ByteStore)mime_parts_decoded.get(msgid+"/"+name);
	} else {
	    return null;
	}
    }

    public Enumeration getMimeParts(String msgid) {
	if(mime_parts_decoded == null) {
	    mime_parts_decoded=new Hashtable();
	}
	Enumeration enum=mime_parts_decoded.keys();
        Vector v=new Vector();
	while(enum.hasMoreElements()) {
	    String key=(String)enum.nextElement();
	    if(key.startsWith(msgid)) {		
		v.addElement(key);
	    }
	}
	return v.elements();
    }
	
    public void clearWork() {
	clearAttachments();
	model.clearWork();
    }

    public void prepareCompose() {
	model.getWorkMessage().getFirstMessageTextPart().addContent("\n--\n",0);
	model.getWorkMessage().getFirstMessageTextPart().addContent(user.getSignature(),0);
    }

    /**
     * This method removes all of the attachments of the current "work" message
     */
    public void clearAttachments() {
	attachments_size=0;
	
	XMLMessage xml_message=model.getWorkMessage();

	String msgid=xml_message.getAttribute("msgid");

	Enumeration enum=getMimeParts(msgid);
	attachments_size=0;
	while(enum.hasMoreElements()) {
	    mime_parts_decoded.remove((String)enum.nextElement());
	}
    }
	
    /**
     * This method returns a table of attachments for the current "work" message
     */
    public Hashtable getAttachments() {
	Hashtable hash=new Hashtable();
	XMLMessage xml_message=model.getWorkMessage();

	String msgid=xml_message.getAttribute("msgid");

	Enumeration enum=getMimeParts(msgid);
	while(enum.hasMoreElements()) {
	    String key=(String)enum.nextElement();
	    String filename=key.substring(msgid.length()+1);
	    hash.put(filename,mime_parts_decoded.get(key));
	}
	
	return hash;
    }

    /**
     * This method returns the attachment with the given name of the current "work" message
     */
    public ByteStore getAttachment(String key) {
	XMLMessage xml_message=model.getWorkMessage();
	String msgid=xml_message.getAttribute("msgid");
	
	return getMIMEPart(msgid,key);
    }

    /**
     * Add an attachment to the current work message.
     * @param name Name of the attachment (e.g. filename)
     * @param bs The contents of the attachment, as a ByteStore object
     * @param description A short description of the contents (will be used as the "Description:" header
     */
    public void addWorkAttachment(String name, ByteStore bs, String description) throws WebMailException {
	XMLMessage xml_message=model.getWorkMessage();
	XMLMessagePart xml_multipart=xml_message.getFirstMessageMultiPart();

	String msgid=xml_message.getAttribute("msgid");

	bs.setDescription(description);

	Enumeration enum=getMimeParts(msgid);
	attachments_size=0;
	while(enum.hasMoreElements()) {
	    ByteStore b=(ByteStore)mime_parts_decoded.get((String)enum.nextElement());
	    attachments_size+=b.getSize();
	}

	int max_size=0;
	try {
	    max_size=Integer.parseInt( parent.getStorage().getConfig("MAX ATTACH SIZE"));
	} catch(NumberFormatException e) {
	    parent.getStorage().log(Storage.LOG_WARN,"Invalid setting for parameter \"MAX ATTACH SIZE\". Must be a number!");
	}
				
	if(attachments_size+bs.getSize() > max_size) {
	    throw new WebMailException("Attachments are too big. The sum of the sizes may not exceed "+max_size+" bytes.");
	} else {
	    mime_parts_decoded.put(msgid+"/"+name,bs);
	    attachments_size+=bs.getSize();
	    XMLMessagePart xml_part=xml_multipart.createPart("binary");
	    
	    xml_part.setAttribute("filename",name);
	    xml_part.setAttribute("size",bs.getSize()+"");
	    xml_part.setAttribute("description",description);
	    xml_part.setAttribute("content-type",bs.getContentType().toLowerCase());
	}
	setEnv();
	//XMLCommon.debugXML(model.getRoot());
    }

    /**
     * Remove the attachment with the given name from the current work message.
     */
    public void removeWorkAttachment(String name) {
	XMLMessage xml_message=model.getWorkMessage();
	XMLMessagePart xml_multipart=xml_message.getFirstMessageMultiPart();

	String msgid=xml_message.getAttribute("msgid");

	mime_parts_decoded.remove(msgid+"/"+name);

	Enumeration enum=getMimeParts(msgid);
	attachments_size=0;
	while(enum.hasMoreElements()) {
	    ByteStore b=(ByteStore)mime_parts_decoded.get((String)enum.nextElement());
	    attachments_size+=b.getSize();
	}
	
	enum=xml_multipart.getParts();
	XMLMessagePart oldpart=null;
	while(enum.hasMoreElements()) {
	    XMLMessagePart tmp=(XMLMessagePart)enum.nextElement();
	    if(tmp.getAttribute("filename") != null &&
	       tmp.getAttribute("filename").equals(name)) {
		oldpart=tmp;
		break;
	    }
	}
	if(oldpart != null) {
	    xml_multipart.removePart(oldpart);
	}
	setEnv();
	//XMLCommon.debugXML(model.getRoot());
    }
	
    /**
     * Store a message in the environment for further processing.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -