abstractredirect.java

来自「java 开发的邮件服务器平台。支持以下协议。 协议可以修改为自己的专门标识」· Java 代码 · 共 1,620 行 · 第 1/5 页

JAVA
1,620
字号
            subjectPrefix       = getSubjectPrefix();            apparentlyTo        = getTo();            attachError         = attachError();            isReply             = isReply();            if (isDebug) {                StringBuffer logBuffer =                    new StringBuffer(1024)                            .append("static")                            .append(", passThrough=").append(passThrough)                            .append(", fakeDomainCheck=").append(fakeDomainCheck)                            .append(", sender=").append(sender)                            .append(", replyTo=").append(replyTo)                            .append(", reversePath=").append(reversePath)                            .append(", message=").append(messageText)                            .append(", recipients=").append(arrayToString(recipients == null ? null : recipients.toArray()))                            .append(", subject=").append(subject)                            .append(", subjectPrefix=").append(subjectPrefix)                            .append(", apparentlyTo=").append(arrayToString(apparentlyTo))                            .append(", attachError=").append(attachError)                            .append(", isReply=").append(isReply)                            .append(", attachmentType=").append(attachmentType)                            .append(", inLineType=").append(inLineType)                            .append(" ");                log(logBuffer.toString());            }        }    }    /**     * Service does the hard work,and redirects the originalMail in the form specified.     *     * @param originalMail the mail to process and redirect     * @throws MessagingException if a problem arises formulating the redirected mail     */    public void service(Mail originalMail) throws MessagingException {        boolean keepMessageId = false;        // duplicates the Mail object, to be able to modify the new mail keeping the original untouched        Mail newMail = ((MailImpl) originalMail).duplicate(newName((MailImpl) originalMail));        // We don't need to use the original Remote Address and Host,        // and doing so would likely cause a loop with spam detecting        // matchers.        try {            ((MailImpl) newMail).setRemoteAddr(java.net.InetAddress.getLocalHost().getHostAddress());            ((MailImpl) newMail).setRemoteHost(java.net.InetAddress.getLocalHost().getHostName());        } catch (java.net.UnknownHostException _) {            ((MailImpl) newMail).setRemoteAddr("127.0.0.1");            ((MailImpl) newMail).setRemoteHost("localhost");        }        if (isDebug) {            MailImpl newMailImpl = (MailImpl) newMail;            log("New mail - sender: " + newMailImpl.getSender()                       + ", recipients: " + arrayToString(newMailImpl.getRecipients().toArray())                       + ", name: " + newMailImpl.getName()                       + ", remoteHost: " + newMailImpl.getRemoteHost()                       + ", remoteAddr: " + newMailImpl.getRemoteAddr()                       + ", state: " + newMailImpl.getState()                       + ", lastUpdated: " + newMailImpl.getLastUpdated()                       + ", errorMessage: " + newMailImpl.getErrorMessage());        }        //Create the message        if(getInLineType(originalMail) != UNALTERED) {            if (isDebug) {                log("Alter message");            }            newMail.setMessage(new MimeMessage(Session.getDefaultInstance(System.getProperties(),                                                               null)));            // handle the new message if altered            buildAlteredMessage(newMail, originalMail);        } else {            // if we need the original, create a copy of this message to redirect            if (getPassThrough(originalMail)) {                newMail.setMessage(new MimeMessage(originalMail.getMessage()) {                    protected void updateHeaders() throws MessagingException {                        if (getMessageID() == null) super.updateHeaders();                        else {                            modified = false;                        }                    }                });            }            if (isDebug) {                log("Message resent unaltered.");            }            keepMessageId = true;        }        //Set additional headers        setRecipients(newMail, getRecipients(originalMail), originalMail);        setTo(newMail, getTo(originalMail), originalMail);        setSubjectPrefix(newMail, getSubjectPrefix(originalMail), originalMail);        if(newMail.getMessage().getHeader(RFC2822Headers.DATE) == null) {            newMail.getMessage().setHeader(RFC2822Headers.DATE, rfc822DateFormat.format(new Date()));        }        setReplyTo(newMail, getReplyTo(originalMail), originalMail);        setReversePath(newMail, getReversePath(originalMail), originalMail);        setSender(newMail, getSender(originalMail), originalMail);        setIsReply(newMail, isReply(originalMail), originalMail);        newMail.getMessage().saveChanges();        if (keepMessageId) {            setMessageId(newMail, originalMail);        }        if (senderDomainIsValid(newMail)) {            //Send it off...            getMailetContext().sendMail(newMail);        } else {            StringBuffer logBuffer = new StringBuffer(256)                                    .append(getMailetName())                                    .append(" mailet cannot forward ")                                    .append(((MailImpl) originalMail).getName())                                    .append(". Invalid sender domain for ")                                    .append(newMail.getSender())                                    .append(". Consider using the Resend mailet ")                                    .append("using a different sender.");            throw new MessagingException(logBuffer.toString());        }        if(!getPassThrough(originalMail)) {            originalMail.setState(Mail.GHOST);        }    }    private static final java.util.Random random = new java.util.Random();  // Used to generate new mail names    /**     * Create a unique new primary key name.     *     * @param mail the mail to use as the basis for the new mail name     * @return a new name     */    private String newName(MailImpl mail) throws MessagingException {        String oldName = mail.getName();                // Checking if the original mail name is too long, perhaps because of a        // loop caused by a configuration error.        // it could cause a "null pointer exception" in AvalonMailRepository much        // harder to understand.        if (oldName.length() > 76) {            int count = 0;            int index = 0;            while ((index = oldName.indexOf('!', index + 1)) >= 0) {                count++;            }            // It looks like a configuration loop. It's better to stop.            if (count > 7) {                throw new MessagingException("Unable to create a new message name: too long."                                             + " Possible loop in config.xml.");            }            else {                oldName = oldName.substring(0, 76);            }        }                StringBuffer nameBuffer =                                 new StringBuffer(64)                                 .append(oldName)                                 .append("-!")                                 .append(random.nextInt(1048576));        return nameBuffer.toString();    }    /**     * A private method to convert types from string to int.     *     * @param param the string type     * @return the corresponding int enumeration     */    protected int getTypeCode(String param) {        param = param.toLowerCase(Locale.US);        if(param.compareTo("unaltered") == 0) {            return UNALTERED;        }        if(param.compareTo("heads") == 0) {            return HEADS;        }        if(param.compareTo("body") == 0) {            return BODY;        }        if(param.compareTo("all") == 0) {            return ALL;        }        if(param.compareTo("none") == 0) {            return NONE;        }        if(param.compareTo("message") == 0) {            return MESSAGE;        }        return NONE;    }    /**     * Gets the MailAddress corresponding to the existing "Return-Path" of     * <I>mail</I>.     * If empty returns <CODE>SpecialAddress.NULL</CODE>,     * if missing return <CODE>null</CODE>.     */    protected MailAddress getExistingReturnPath(Mail mail) throws MessagingException {        MailAddress mailAddress = null;        String[] returnPathHeaders = mail.getMessage().getHeader(RFC2822Headers.RETURN_PATH);        String returnPathHeader = null;        if (returnPathHeaders != null) {            returnPathHeader = returnPathHeaders[0];            if (returnPathHeader != null) {                returnPathHeader = returnPathHeader.trim();                if (returnPathHeader.equals("<>")) {                    mailAddress = SpecialAddress.NULL;                } else {                    mailAddress = new MailAddress(new InternetAddress(returnPathHeader));                }            }        }        return mailAddress;    }    /**     * Utility method for obtaining a string representation of an array of Objects.     */    private String arrayToString(Object[] array) {        if (array == null) {            return "null";        }        StringBuffer sb = new StringBuffer(1024);        sb.append("[");        for (int i = 0; i < array.length; i++) {            if (i > 0) {                sb.append(",");            }            sb.append(array[i]);        }        sb.append("]");        return sb.toString();    }    /**     * Utility method for obtaining a string representation of a     * Message's headers     */    private String getMessageHeaders(MimeMessage message) throws MessagingException {        Enumeration heads = message.getAllHeaderLines();        StringBuffer headBuffer = new StringBuffer(1024);        while(heads.hasMoreElements()) {            headBuffer.append(heads.nextElement().toString()).append("\r\n");        }        return headBuffer.toString();    }    /**     * Utility method for obtaining a string representation of a     * Message's body     */    private String getMessageBody(MimeMessage message) throws Exception {        java.io.InputStream bis = null;        java.io.OutputStream bos = null;        java.io.ByteArrayOutputStream bodyOs = new java.io.ByteArrayOutputStream();        try {            // Get the message as a stream.  This will encode            // objects as necessary, and we have some overhead from            // decoding and re-encoding the stream.  I'd prefer the            // raw stream, but see the WARNING below.            bos = javax.mail.internet.MimeUtility.encode(bodyOs, message.getEncoding());            bis = message.getInputStream();        } catch(javax.activation.UnsupportedDataTypeException udte) {            /* If we get an UnsupportedDataTypeException try using             * the raw input stream as a "best attempt" at rendering             * a message.             *             * WARNING: JavaMail v1.3 getRawInputStream() returns             * INVALID (unchanged) content for a changed message.             * getInputStream() works properly, but in this case             * has failed due to a missing DataHandler.             *             * MimeMessage.getRawInputStream() may throw a "no             * content" MessagingException.  In JavaMail v1.3, when             * you initially create a message using MimeMessage             * APIs, there is no raw content available.             * getInputStream() works, but getRawInputStream()             * throws an exception.  If we catch that exception,             * throw the UDTE.  It should mean that someone has             * locally constructed a message part for which JavaMail             * doesn't have a DataHandler.             */            try {                bis = message.getRawInputStream();                bos = bodyOs;            } catch(javax.mail.MessagingException _) {                throw udte;            }        }        catch(javax.mail.MessagingException me) {            /* This could be another kind of MessagingException             * thrown by MimeMessage.getInputStream(), such as a             * javax.mail.internet.ParseException.             *             * The ParseException is precisely one of the reasons             * why the getRawInputStream() method exists, so that we             * can continue to stream the content, even if we cannot             * handle it.  Again, if we get an exception, we throw             * the one that caused us to call getRawInputStream().             */            try {                bis = message.getRawInputStream();                bos = bodyOs;            } catch(javax.mail.MessagingException _) {                throw me;            }        }

⌨️ 快捷键说明

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