📄 messageutilities.java
字号:
/*** $Id: MessageUtilities.java,v 1.6 2001/05/07 12:37:22 kunugi Exp $**** Copyright (c) 2000-2001 Jeff Gay** on behalf of ICEMail.org <http://www.icemail.org>** Copyright (c) 1998-2000 by Timothy Gerard Endres** ** This program is free software.** ** You may redistribute it and/or modify it under the terms of the GNU** General Public License as published by the Free Software Foundation.** Version 2 of the license should be included with this distribution in** the file LICENSE, as well as License.html. If the license is not** included with this distribution, you may find a copy at the FSF web** site at 'www.gnu.org' or 'www.fsf.org', or you may write to the** Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139 USA.**** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND,** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR** REDISTRIBUTION OF THIS SOFTWARE. */package org.icemail.mail;import java.io.BufferedReader;import java.io.File;import java.io.InputStream;import java.io.InputStreamReader;import java.io.IOException;import java.io.StringReader;import java.io.UnsupportedEncodingException;import java.util.Enumeration;import java.util.Hashtable;import java.util.Vector;import javax.activation.DataHandler;import javax.activation.FileDataSource;import javax.activation.MimeTypeParseException;import javax.mail.Address;import javax.mail.Header;import javax.mail.Message;import javax.mail.MessagingException;import javax.mail.Part;import javax.mail.Multipart;import javax.mail.internet.ContentType;import javax.mail.internet.InternetAddress;import javax.mail.internet.InternetHeaders;import javax.mail.internet.MimeBodyPart;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeMultipart;import javax.mail.internet.MimePart;import javax.mail.internet.MimeUtility;import javax.mail.internet.ParseException;import org.icemail.util.UserProperties;/** * Message parsing and generation utility routines. */public class MessageUtilities{ /** * This wrapper is used to work around a bug in the sun io inside * sun.io.ByteToCharConverter.getConverterClass(). * * The programmer uses a cute coding trick * that appends the charset to a prefix to create a Class name that * they then attempt to load. The problem is that if the charset is * not one that they "recognize", and the name has something like a * dash character in it, the resulting Class name has an invalid * character in it. This results in an IllegalArgumentException * instead of the UnsupportedEncodingException that is documented. * Thus, we need to catch the undocumented exception. * * @param part The part from which to get the content. * @return The content. * @exception MessagingException if the content charset is unsupported. * */ public static Object getPartContent( Part part ) throws MessagingException { Object result = null; try { result = part.getContent(); } catch ( IllegalArgumentException ex ) { throw new MessagingException( "content charset is not recognized: " + ex.getMessage() ); } catch ( IOException ex ) { throw new MessagingException( "getPartContent(): " + ex.getMessage() ); } return result; } /** * This wrapper is used to work around a bug in the sun io inside * sun.io.ByteToCharConverter.getConverterClass(). * * The programmer uses a cute coding trick * that appends the charset to a prefix to create a Class name that * they then attempt to load. The problem is that if the charset is * not one that they "recognize", and the name has something like a * dash character in it, the resulting Class name has an invalid * character in it. This results in an IllegalArgumentException * instead of the UnsupportedEncodingException that is documented. * Thus, we need to catch the undocumented exception. * * @param dh The DataHandler from which to get the content. * @return The content. * @exception MessagingException if the content charset is unsupported. * */ public static Object getDataHandlerContent( DataHandler dh ) throws MessagingException { Object result = null; try { result = dh.getContent(); } catch ( IllegalArgumentException ex ) { throw new MessagingException( "content charset is not recognized: " + ex.getMessage() ); } catch ( IOException ex ) { throw new MessagingException( "getDataHandlerContent(): " + ex.getMessage() ); } return result; } /** * Create a reply message to the given message. * The reply message is addressed to only the from / reply address or * all receipients based on the replyToAll flag. * * @param message The message which to reply * @param body The attached text to include in the reply * @param replyToAll Reply to all receipients of the original message * @return Message Reply message * @exception MessagingException if the message contents are invalid */ public static Message createReply( Message message, String body, boolean replyToAll ) throws MessagingException { // create an empty reply message Message xreply = message.reply( replyToAll ); // set the default from address xreply.setFrom( MessageUtilities.getDefaultFromAddress() ); // UNDONE should any extra headers be replied to? if ( message instanceof MimeMessage ) { ((MimeMessage) xreply).setText( body, "UTF-8" ); } else { xreply.setText( body ); } // Message.reply() may set the "replied to" flag, so // attempt to save that new state and fail silently... try { message.saveChanges(); } catch ( MessagingException ex ) { } return xreply; } /** * Create a forward message to the given message. * The forward message addresses no receipients but * contains all the contents of the given message. * Another missing method in JavaMail!!! * * @param message The message which to forward * @return Message Forwarding message * @exception MessagingException if the message contents are invalid */ public static Message createForward( Message message ) throws MessagingException { // create an initial message without addresses, subject, or content MimeMessage xforward = new MimeMessage( ICEMail.getDefaultSession() ); // create forwarding headers InternetHeaders xheaders = MessageUtilities.getHeaders( message ); xheaders.removeHeader( "from" ); xheaders.removeHeader( "to" ); xheaders.removeHeader( "cc" ); xheaders.removeHeader( "bcc" ); xheaders.removeHeader( "received" ); MessageUtilities.addHeaders( xforward, xheaders ); // set the default from address xforward.setFrom( MessageUtilities.getDefaultFromAddress() ); // create the subject String xsubject = message.getSubject().trim(); if ( xsubject.toUpperCase().indexOf( "FW" ) != 0 ) { xsubject = "FW: " + xsubject; } xforward.setSubject( xsubject, "UTF-8" ); // create the contents ContentType xctype = MessageUtilities.getContentType( message ); Object xcont = MessageUtilities.getPartContent( message ); xforward.setContent( xcont, xctype.toString() ); // REVIEW - why would we need to save here?! // xforward.saveChanges(); return xforward; }//............................................................ /** * Decode from address(es) of the message into UTF strings. * This is a convenience method provided to simplify application code. * * @param message The message to interogate * @return String List of decoded addresses * @exception MessagingException if the message contents are invalid */ public static String decodeFrom( Message message ) throws MessagingException { Address[] xaddresses = message.getFrom(); return decodeAddresses( xaddresses ); } /** * Decode recipent addresses of the message into UTF strings. * This is a convenience method provided to simplify application code. * * @param message The message to interogate * @param type The type of message recipients to decode, i.e. from, to, cc, etc * @return String List of decoded addresses * @exception MessagingException if the message contents are invalid */ public static String decodeAddresses( Message message, Message.RecipientType type ) throws MessagingException { Address[] xaddresses = message.getRecipients( type ); return decodeAddresses( xaddresses ); } /** * Decode mail addresses into UTF strings. * <p> * This routine is necessary because Java Mail Address.toString() routines * convert into MIME encoded strings (ASCII C and B encodings), not UTF. * Of course, the returned string is in the same format as MIME, but converts * to UTF character encodings. * * @param addresses The list of addresses to decode * @return String List of decoded addresses */ public static String decodeAddresses( Address[] addresses ) { StringBuffer xlist = new StringBuffer(); if ( addresses != null ) { for ( int xindex = 0 ; xindex < addresses.length ; xindex++ ) { // at this time, only internet addresses can be decoded if ( xlist.length() > 0 ) xlist.append( ", " ); if ( addresses[xindex] instanceof InternetAddress ) { InternetAddress xinet = (InternetAddress)addresses[ xindex ]; if ( xinet.getPersonal() == null ) { xlist.append( xinet.getAddress() ); } else { // If the address has a ',' in it, we must // wrap it in quotes, or it will confuse the // code that parses addresses separated by commas. String personal = xinet.getPersonal(); int idx = personal.indexOf( "," ); String qStr = ( idx == -1 ? "" : "\"" ); xlist.append( qStr ); xlist.append( personal ); xlist.append( qStr ); xlist.append( " <" ); xlist.append( xinet.getAddress() ); xlist.append( ">" ); } } else { // generic, and probably not portable, // but what's a man to do... xlist.append( addresses[xindex].toString() ); } } } return xlist.toString(); } /** * Encode UTF strings into mail addresses. */ public static InternetAddress[] encodeAddresses( String string, String charset ) throws MessagingException { // parse the string into the internet addresses // NOTE: these will NOT be character encoded InternetAddress[] xaddresses = InternetAddress.parse( string ); // now encode each to the given character set for ( int xindex = 0; xindex < xaddresses.length; xindex++ ) { String xpersonal = xaddresses[xindex].getPersonal(); try { if ( xpersonal != null ) { xaddresses[xindex].setPersonal( xpersonal, charset ); } } catch ( UnsupportedEncodingException xex ) { throw new MessagingException( xex.toString() ); } } return xaddresses; } public static InternetAddress getDefaultFromAddress() throws MessagingException { // encode the address
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -