emailtask.java

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

JAVA
421
字号
/** * $RCSfile: EmailTask.java,v $ * $Revision: 1.6 $ * $Date: 2002/08/05 22:22:43 $ * * Copyright (C) 1999-2002 CoolServlets, Inc. All rights reserved. * * This software is the proprietary information of CoolServlets, Inc. * Use is subject to license terms. */package com.jivesoftware.forum.util;import com.jivesoftware.forum.JiveGlobals;import com.jivesoftware.util.Semaphore;import javax.mail.*;import javax.mail.internet.*;import java.security.Security;import java.util.*;/** * A task to send email.<p> * * This class will hold a list of messages and will send them all at once when * the <code>run</code> method is called.<p> * * This class has a few factory methods you can use to return message objects * or to add messages into a queue to be sent. Using these methods, you can * send emails in the following couple of ways:<p> * <pre> *   TaskEngine taskEngine = new TaskEngine(); *   EmailTask emailTask = new EmailTask(); *   emailTask.addMessage( *     "Joe Bloe", "jbloe@place.org", *     "Jane Doe", "jane@doe.com", *     "Hello...", *     "This is the body of the email..." *   ); *   taskEngine.addTask(emailTask, Thread.NORM_PRIORITY); * </pre> * or * <pre> *   TaskEngine taskEngine = new TaskEngine(); *   EmailTask emailTask = new EmailTask(); *   Message message = emailTask.createMessage(); *   // call setters on the message object *   // . *   // . *   // . *   taskEngine.addTask(emailTask, Thread.NORM_PRIORITY); * </pre><p> * * This class is configured with a set of Jive properties:<ul> *      <li><tt>mail.smtp.host</tt> -- the host name of your mail server, i.e. *          mail.yourhost.com *      <li><tt>mail.smtp.port</tt> -- an optional property to change the smtp *          port used from the default of 25. *      <li><tt>mail.smtp.username</tt> -- an optional property to change the *          username used to connect to the smtp server. Default is no username. *      <li><tt>mail.smtp.password</tt> -- an optional property to change the *          password used to connect to the smtp server. Default is no password. *      <li><tt>mail.smtp.ssl</tt> -- an optional property to set whether to use *          SSL to connect to the smtp server or not. Default is false. * </ul> * * @see TaskEngine */public class EmailTask implements Runnable {    // class that will send the messages for us    private SmtpProxy smtpProxy;    private static String host     = JiveGlobals.getJiveProperty("mail.smtp.host");    private static String port     = JiveGlobals.getJiveProperty("mail.smtp.port");    private static String username = JiveGlobals.getJiveProperty("mail.smtp.username");    private static String password = JiveGlobals.getJiveProperty("mail.smtp.password");    private static String ssl      = JiveGlobals.getJiveProperty("mail.smtp.ssl");    private static String debug    = JiveGlobals.getJiveProperty("mail.debug");    // The total number of simultaneous connections allowed to the smtp server    private static final long MAX_SMTP_CONNECTIONS = 5;    private static final Semaphore smtpSemaphore = new Semaphore(MAX_SMTP_CONNECTIONS);    // List of messages    private List messages = null;    /**     * Creates a new EmailTask.     */    public EmailTask() {        messages  = Collections.synchronizedList(new ArrayList());        smtpProxy = new SmtpProxy();        smtpProxy.setHost(host);        if (port != null) {            try {                smtpProxy.setPort(Integer.parseInt(port));            } catch (Exception ignored) {}        }        smtpProxy.setUsername(username);        smtpProxy.setPassword(password);        smtpProxy.setSSLEnabled(Boolean.valueOf(ssl).booleanValue());        smtpProxy.setDebugEnabled(Boolean.valueOf(debug).booleanValue());    }    /**     * Runs the task, which sends all email messages that have been queued.     */    public void run() {        // get one of the available smtp connections        try {            smtpSemaphore.acquire();        }        catch (InterruptedException e) {            e.printStackTrace();        }        try {            smtpProxy.send(messages);            messages.clear();        }        catch (MessagingException e) {            e.printStackTrace();        }        smtpSemaphore.release();    }    /**     * Factory method to add a JavaMail message object to the internal list     * of messages.     *     * @param message a message to send.     */    public void addMessage(Message message) {        if (message != null) {            messages.add(message);        }        else {            System.err.println("Cannot add null email message to queue.");        }    }    /**     * Factory method to add a message by specifying its fields.<p>     *     * To use more advanced message features, use the     * <code>addMessage(Message message)</code> method.<p>     *     * If parts of the message are invalid (ie, the toEmail is null) the message     * won't be sent.     *     * @param toName the name of the recipient of this email.     * @param toEmail the email address of the recipient of this email.     * @param fromName the name of the sender of this email.     * @param fromEmail the email address of the sender of this email.     * @param subject the subject of the email.     * @param body the body of the email.     */    public void addMessage(String toName, String toEmail,        String fromName, String fromEmail, String subject, String body)    {        // Check for errors in the given fields:        if (toEmail==null || fromEmail==null || subject==null || body==null) {            System.err.println("Error sending email in EmailTask.java: "                + "Invalid fields.");        }        else {            try {                // Use the global Jive encoding for the emails.                String encoding = MimeUtility.mimeCharset(JiveGlobals.getCharacterEncoding());                MimeMessage message = createMessage();                Address to   = null;                Address from = null;                if (toName != null) {                    to = new InternetAddress(toEmail, toName, encoding);                }                else {                    to = new InternetAddress(toEmail, "", encoding);                }                if (fromName != null) {                    from = new InternetAddress(fromEmail, fromName, encoding);                }                else {                    from = new InternetAddress(fromEmail, "", encoding);                }                message.setRecipient(Message.RecipientType.TO, to);                message.setFrom(from);                message.setSubject(subject, encoding);                // Use the correct encoding and content-type for the message                MimeBodyPart bPart = new MimeBodyPart();                bPart.setText(body, encoding);                bPart.setDisposition(Part.INLINE);                MimeMultipart mPart = new MimeMultipart();                mPart.addBodyPart(bPart);                message.setContent(mPart);                message.setDisposition(Part.INLINE);                // Add the message to the send list                addMessage(message);            }            catch (Exception e) {                e.printStackTrace();            }        }    }    /**     * Factory method to return a blank JavaMail message. You should use the     * object returned and set desired message properties. When done, pass the     * object to the addMessage(Message) method.     *     * @return A new JavaMail message.     */    public MimeMessage createMessage() {        return smtpProxy.createMessage();    }    /**     * A small class that handles the actual sending of the mail.     */    private class SmtpProxy {        private Session session = null;        private String host     = null;        private int    port     = 25;        private String username = null;        private String password = null;        private boolean SSLEnabled = false;        private boolean debugEnabled = false;        /**         * Specify the factory that javamail should use for SSL connections         * to the server.         */        private static final String SSL_FACTORY =            "com.jivesoftware.forum.gateway.ssl.DummySSLSocketFactory";        /**         * Create a new instance.         */        public SmtpProxy() {}        /**         * Sets the SMTP host (eg mail.example.com). The host is null by         * default, but must be set before gateway exports can execute.         *         * @param host The SMTP host.         */        public void setHost(String host) {            this.host = host;            // JavaMail Session no longer valid so set to null; it will get            // recreated as needed.            session = null;        }        /**         * Sets the port number that will be used when connecting to the SMTP         * server. The default is 25, the standard SMTP port number.         *         * @param port The SMTP port number.         */        public void setPort(int port) {            this.port = port;            // JavaMail Session no longer valid so set to null; it will get            // recreated as needed.            session = null;        }        /**         * Sets the username that will be used when connecting to the SMTP         * server. The default is null, or no username.         *         * @param username The SMTP username.         */        public void setUsername(String username) {            this.username = username;            // JavaMail Session no longer valid so set to null; it will get            // recreated as needed.            session = null;        }        /**         * Sets the username that will be used when connecting to the SMTP         * server. The default is null, or no username.         *         * @param password The SMTP password.         */        public void setPassword(String password) {            this.password = password;            // JavaMail Session no longer valid so set to null; it will get            // recreated as needed.            session = null;        }        /**         * Toggles SMTP transport layer debugging on or off. Debug information is         * written to <tt>System.out</tt> by the underlying JavaMail provider.         *         * @param debugEnabled True if SMTP debugging should be enabled.         */        public void setDebugEnabled(boolean debugEnabled) {            this.debugEnabled = debugEnabled;            // JavaMail SMTP Session no longer valid so set to null; it will get            // recreated as needed.            session = null;        }        /**         * 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;        }        /**         * Create a new MimeMessage.         *         * @return MimeMessage A new message object.         */        public MimeMessage createMessage() {            return new MimeMessage(session);        }        /**         * Send messages.         *         * @param messages The mail objects to send.         * @throws MessagingException If a connection was unable to be established.         */        public void send(List messages) throws MessagingException {            // If there are no messages, do nothing.            if (messages.size() == 0) {                return;            }            retrieveSession();            Transport transport = null;            try {                transport = connectToSmtpServer();                MimeMessage message;                Iterator iter = messages.iterator();                while (iter.hasNext()) {                    message = (MimeMessage)iter.next();                    // Attempt to send message, but catch exceptions caused by invalid                    // addresses so that other messages can continue to be sent.                    try {                        transport.sendMessage(message,                            message.getRecipients(MimeMessage.RecipientType.TO));                    }                    catch (AddressException ae) {                        ae.printStackTrace();                    }                }            }            finally {                if (transport != null) {                    try {                        disconnectFromSmtpServer(transport);                    }                    catch (MessagingException e) { /* ignore */ }                }                session = null;            }        }        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");                }                // If a username is defined, use SMTP authentication.                if (username != null) {                    mailProps.put("mail.smtp.auth", "true");                }                session = Session.getInstance(mailProps, null);            }        }        private Transport connectToSmtpServer() throws MessagingException {            URLName url = new URLName("smtp", host, port, "", username, password);            Transport trans =                    (Transport) 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();        }    }}

⌨️ 快捷键说明

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