smtpexporter.java

来自「Jive是基于JSP/JAVA技术构架的一个大型BBS论坛系统,这是Jive论坛」· Java 代码 · 共 765 行 · 第 1/2 页

JAVA
765 行
字号
    /**     * Set the from email address for message export.     *     * @param address     */    public void setDefaultFromAddress(String address) {        if ("".equals(address)) {            address = null;        }        this.defaultFromAddress = address;    }    /**     * Returns the reply to address for export.     *     * @return the reply to address.     */    public String getReplyToAddress() {        return replyToAddress;    }    /**     * Set the reply-to email address for message export.     *     * @param address     */    public void setReplyToAddress(String address) {        if ("".equals(address)) {            address = null;        }        this.replyToAddress = address;    }    /**     * Checks to see if this gateway is configured for SSL     * connections to the SMTP server or not. Unlike most     * standard SSL connections to the SMTP server are often     * on the same port as unencrypted connections (port 25).     */    public boolean isSSLEnabled() {        return SSLEnabled;    }    /**     * Sets whether this gateway is configured for SSL connections     * to the SMTP server or not.     *     * @param SSLEnabled true if ssl should be enabled, false otherwise.     */    public void setSSLEnabled(boolean SSLEnabled) {        this.SSLEnabled = SSLEnabled;        // JavaMail Session no longer valid so set to null; it will get        // recreated as needed.        session = null;    }    /**     * Retrieves the Organization header for outbound     * smtp messages. Default is null.     *     * @return the current organization header.     */    public String getOrganization() {        return organization;    }    /**     * Sets the Organization header for outbound smtp messages.     *     * @param organization the string to set the organization header to.     */    public void setOrganization(String organization) {        this.organization = organization;    }    /**     * Retrieve whether the gateway will update the messageID     * message property stored in Jive upon export of a message.     * By default, the messageID is stored in Jive so that the     * message won't be reexported accidentally.<p>     *     * Note: This setting has no effect unless accompanied by     * setAllowExportAgain(true).     *     * @return true if the gateway will update Jive with the messageID     *         on export, false otherwise.     */    public boolean isUpdateMessageIDOnExport() {        return updateMessageID;    }    /**     * Sets whether the gateway will update the messageID     * message property stored in Jive upon export of a message.     * By default, the messageID is stored in Jive so that the     * message won't be reexported accidentally.<p>     *     * Note: This setting has no effect unless accompanied by     * setAllowExportAgain(true).     *     * @param updateMessageID true if Jive should be updated with the messageID     *        of exported messages, false otherwise.     */    public void setUpdateMessageIDOnExport(boolean updateMessageID) {        this.updateMessageID = updateMessageID;    }    /**     * Return whether this gateway will allow reexporting of messages     * or not. Default is false.     *     * @return whether reexporting a message is allowed or not.     */    public boolean isAllowExportAgain() {        return exportIgnoreMessageID;    }    /**     * By default this gateway refuses to re-export a message which has     * previously been exported or imported or which was automatically     * created for threading purposes by an import gateway.<p>     *     * However this can be overridden so that messages can be re-exported     * again if absolutely needed. Definite care is needed if you set     * the property to true.<p>     *     * Please note however that dummy messages will *never* be exported.     *     * @param allowExportAgain true if messages should be allowed to be     *        reexported, false otherwise.     */    public void setAllowExportAgain(boolean allowExportAgain) {        this.exportIgnoreMessageID = allowExportAgain;    }    public boolean isAttachmentsEnabled() {        return attachmentEnabled;    }    public void setAttachmentsEnabled(boolean attachmentsEnabled) {        try {            LicenseManager.validateLicense("Jive Forums Professional", "2.0");        }        catch (LicenseException e) {            this.attachmentEnabled = false;            return;        }        this.attachmentEnabled = attachmentsEnabled;    }    private void retrieveSession() {        // enabled SSL        if (SSLEnabled) {            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());            Security.setProperty("ssl.SocketFactory.provider", SSL_FACTORY);        }        // Create the mail session if necessary.        if (session == null) {            Properties mailProps = new Properties();            mailProps.setProperty("mail.smtp.host", host);            mailProps.setProperty("mail.smtp.port", String.valueOf(port));            mailProps.setProperty("mail.debug", String.valueOf(debugEnabled));            // Methology from an article on www.javaworld.com (Java Tip 115)            // We will attempt to failback to an insecure connection            // if the secure one cannot be made            if (SSLEnabled) {                mailProps.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);                mailProps.setProperty("mail.smtp.socketFactory.fallback", "true");            }            session = Session.getInstance(mailProps, null);        }    }    private MimeMessage createMessage(ForumMessage forumMessage)            throws GatewayException    {        try {            MimeMessage message = new MimeMessage(session);            InternetAddress to = new InternetAddress(toAddress);            String subject = (!"".equals(forumMessage.getSubject()))                                ? forumMessage.getSubject() : " ";            message.setFrom(getFromAddress(forumMessage));            if (replyToAddress != null) {                Address[] replyTo = new InternetAddress[] { new InternetAddress(replyToAddress) };                message.setReplyTo(replyTo);            }            message.setRecipient(Message.RecipientType.TO, to);            message.setSubject(subject, "ISO-8859-1");            if (organization != null) {                message.setHeader("Organization", organization);            }            // Get a parent message ID if one exists so we can set            // the references header properly for threading to work.            try {                ForumThread thread = forumMessage.getForumThread();                TreeWalker tree = thread.treeWalker();                ForumMessage parent = tree.getParent(forumMessage);                String parentID = parent.getProperty(gatewayMessageId);                if (parentID != null && !parentID.equals("")) {                    message.setHeader("In-Reply-To", parentID);                }            }            catch (ForumMessageNotFoundException fmnfe) {                // no parent, ignore            }            // add body            addContent(forumMessage, message);            // save all the changes to the message            message.saveChanges();            return message;        }        catch (MessagingException e) {            throw new GatewayException(e);        }    }    private Transport connectToSmtpServer()            throws MessagingException    {        URLName url =                new URLName("smtp", host, port, "", username, password);        Transport trans = new com.sun.mail.smtp.SMTPTransport(session, url);        trans.connect(host, port, username, password);        return trans;    }    private void disconnectFromSmtpServer(Transport transport)            throws MessagingException    {        transport.close();    }    /**     * Determine the "from" address, which will normally be     * the message author's name and email address. However, we have to     * use a default address in some circumstances when that info isn't     * available.     *     * @param forumMessage the message for which we are trying to extract     *                     the from address.     * @return InternetAddress the from address.     */    private InternetAddress getFromAddress(ForumMessage forumMessage) {        InternetAddress fromAddress = null;        try {            if (fromAddressOnly) {                fromAddress = new InternetAddress(defaultFromAddress);            }            else if (!forumMessage.isAnonymous()) {                User user = forumMessage.getUser();                String name, email = null;                // Get the name, or use their username if the name is hidden.                if (user.isNameVisible()) {                    name = user.getName();                }                else {                    name = user.getUsername();                }                // Get their email address, or use the dummy address if their                // email is hidden and the admin hasn't overriden that.                if (!user.isEmailVisible() && emailPrefEnabled) {                    email = defaultFromAddress;                }                else {                    email = user.getEmail();                }                fromAddress = new InternetAddress(email, name, "ISO-8859-1");            }            // Message was posted anonymously. However, a name and email might            // be defined through extended properties.            else if (forumMessage.getProperty("name") != null &&                     forumMessage.getProperty("email") != null)            {                String name  = forumMessage.getProperty("name");                String email = forumMessage.getProperty("email");                fromAddress = new InternetAddress(email, name, "ISO-8859-1");            }            // Message was posted anonymously. However, a name might            // be defined through extended properties.            else if (forumMessage.getProperty("name") != null)            {                String name  = forumMessage.getProperty("name");                fromAddress = new InternetAddress(defaultFromAddress, name, "ISO-8859-1");            }            // Message was posted anonymously. However, an email might            // be defined through extended properties.            else if (forumMessage.getProperty("email") != null)            {                String email = forumMessage.getProperty("email");                fromAddress = new InternetAddress(email, "", "ISO-8859-1");            }            // Getting "from" address failed. Use the default address.            else {                fromAddress = new InternetAddress(defaultFromAddress);            }        }        catch (UnsupportedEncodingException e) {            fromAddress = null;        }        catch (AddressException e) {            fromAddress = null;        }        return fromAddress;    }    /**     * Utility method to add ForumMessage content and attachments     * to a MimeMessage.     *     * @throws GatewayException If anything goes wrong.     */    private void addContent(ForumMessage forumMessage, MimeMessage message)            throws GatewayException    {        try {            // The body is the message + the footer.            StringBuffer body = new StringBuffer(forumMessage.getUnfilteredBody());            Forum forum = factory.getForum(forumID);            GatewayManager manager = forum.getGatewayManager();            body.append(manager.getTranslatedFooter(forumMessage));            // check for attachments, handle differently if we have them            if (attachmentEnabled && forumMessage.getAttachmentCount() > 0) {                // Create the message body part, add text content                Multipart multipart = new MimeMultipart();                MimeBodyPart messageBodyPart = new MimeBodyPart();                messageBodyPart.setText(body.toString(), "ISO-8859-1");                messageBodyPart.setDisposition(Part.INLINE);                multipart.addBodyPart(messageBodyPart);                Iterator iter = forumMessage.attachments();                // add each attachment to the message                while (iter.hasNext()) {                    Attachment attachment = (Attachment) iter.next();                    AttachmentDataSource source = new AttachmentDataSource(attachment);                    messageBodyPart = new MimeBodyPart();                    messageBodyPart.setDisposition(Part.ATTACHMENT);                    messageBodyPart.setFileName(attachment.getName());                    messageBodyPart.setDataHandler(new DataHandler(source));                    multipart.addBodyPart(messageBodyPart);                }                // Put parts in message                message.setContent(multipart);            }            else {                message.setText(body.toString(), "ISO-8859-1");            }        }        catch (ForumNotFoundException e) {            throw new GatewayException("ForumNotFoundException thrown", e);        }        catch (MessagingException e) {            throw new GatewayException("MessagingException thrown", e);        }        catch (UnauthorizedException e) {            throw new GatewayException("UnauthorizedException thrown", e);        }        catch (IOException e) {            throw new GatewayException("IOException thrown", e);        }    }}

⌨️ 快捷键说明

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