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

📄 mailutil.java

📁 jspwiki source code,jspwiki source code
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
     * <p>The e-mail address used for the <code>to</code> parameter must be in     * RFC822 format, as described in the JavaDoc for {@link javax.mail.internet.InternetAddress}     * and more fully at     * <a href="http://www.freesoft.org/CIE/RFC/822/index.htm">http://www.freesoft.org/CIE/RFC/822/index.htm</a>.     * In other words, e-mail addresses should look like this:</p>     * <blockquote><code>Snoop Dog &lt;snoop.dog@shizzle.net&gt;<br/>     * snoop.dog@shizzle.net</code></blockquote>     * <p>Note that the first form allows a "friendly" user name to be supplied     * in addition to the actual e-mail address.</p>     *     * @param engine the WikiEngine for the current wiki     * @param to the receiver     * @param subject the subject line of the message     * @param content the contents of the mail message, as plain text     * @throws AddressException If the address is invalid     * @throws MessagingException If the message cannot be sent.     */    public static void sendMessage(WikiEngine engine, String to, String subject, String content)        throws AddressException, MessagingException    {        Properties props = engine.getWikiProperties();        Session session = getMailSession(engine);        getSenderEmailAddress(session, props);        try        {            // Create and address the message            MimeMessage msg = new MimeMessage(session);            msg.setFrom(new InternetAddress(c_fromAddress));            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));            msg.setSubject(subject);            msg.setText(content, "UTF-8");            msg.setSentDate(new Date());            // Send and log it            Transport.send(msg);            if (log.isInfoEnabled())            {                log.info("Sent e-mail to=" + to + ", subject=\"" + subject + "\", used "                         + (c_useJndi ? "JNDI" : "standalone") + " mail session.");            }        }        catch (MessagingException e)        {            log.error(e);            throw e;        }    }        // --------- JavaMail Session Helper methods  --------------------------------    /**     * Gets the Sender's email address from JNDI Session if available, otherwise     * from the jspwiki.properties or lastly the default value.     * @param pSession <code>Session</code>     * @param pProperties <code>Properties</code>     * @return <code>String</code>     */    protected static String getSenderEmailAddress(Session pSession, Properties pProperties)    {        if( c_fromAddress == null )        {            // First, attempt to get the email address from the JNDI Mail            // Session.            if( pSession != null && c_useJndi )            {                c_fromAddress = pSession.getProperty( MailUtil.PROP_MAIL_SENDER );            }            // If unsuccessful, get the email address from the properties or            // default.            if( c_fromAddress == null )            {                c_fromAddress = pProperties.getProperty( PROP_MAIL_SENDER, DEFAULT_SENDER ).trim();                if( log.isDebugEnabled() )                    log.debug( "Attempt to get the sender's mail address from the JNDI mail session failed, will use \""                               + c_fromAddress + "\" (configured via jspwiki.properties or the internal default)." );            }            else            {                if( log.isDebugEnabled() )                    log.debug( "Attempt to get the sender's mail address from the JNDI mail session was successful (" + c_fromAddress                               + ")." );            }        }        return c_fromAddress;    }    /**     * Returns the Mail Session from either JNDI or creates a stand-alone.     * @param engine a <code>WikiEngine</code>     * @return <code>Session</code>     */    private static Session getMailSession(WikiEngine engine)    {        Session result = null;        Properties props = engine.getWikiProperties();        String jndiName = props.getProperty(PROP_MAIL_JNDI_NAME, DEFAULT_MAIL_JNDI_NAME).trim();        if (c_useJndi)        {            // Try getting the Session from the JNDI factory first            if ( log.isDebugEnabled() )                log.debug("Try getting a mail session via JNDI name \"" + jndiName + "\".");            try            {                result = getJNDIMailSession(jndiName);            }            catch (NamingException e)            {                // Oops! JNDI factory must not be set up                c_useJndi = false;                if ( log.isInfoEnabled() )                    log.info("Unable to get a mail session via JNDI, will use custom settings at least until next startup.");            }        }        // JNDI failed; so, get the Session from the standalone factory        if (result == null)        {            if ( log.isDebugEnabled() )                log.debug("Getting a standalone mail session configured by jspwiki.properties and/or internal default values.");            result = getStandaloneMailSession(props);        }        return result;    }    /**     * Returns a stand-alone JavaMail Session by looking up the correct     * mail account, password and host from a supplied set of properties.     * If the JavaMail property {@value #PROP_MAIL_ACCOUNT} is set to     * a value that is non-<code>null</code> and of non-zero length, the     * Session will be initialized with an instance of     * {@link javax.mail.Authenticator}.     * @param props the properties that contain mail session properties     * @return the initialized JavaMail Session     */    protected static Session getStandaloneMailSession( Properties props )    {        // Read the JSPWiki settings from the properties        String host     = props.getProperty( PROP_MAIL_HOST, DEFAULT_MAIL_HOST );        String port     = props.getProperty( PROP_MAIL_PORT, DEFAULT_MAIL_PORT );        String account  = props.getProperty( PROP_MAIL_ACCOUNT );        String password = props.getProperty( PROP_MAIL_PASSWORD );        String timeout  = props.getProperty( PROP_MAIL_TIMEOUT, DEFAULT_MAIL_TIMEOUT);        String conntimeout = props.getProperty( PROP_MAIL_CONNECTION_TIMEOUT, DEFAULT_MAIL_CONN_TIMEOUT );        boolean starttls = TextUtil.getBooleanProperty( props, PROP_MAIL_STARTTLS, true);                boolean useAuthentication = account != null && account.length() > 0;        Properties mailProps = new Properties();        // Set JavaMail properties        mailProps.put( PROP_MAIL_HOST, host );        mailProps.put( PROP_MAIL_PORT, port );        mailProps.put( PROP_MAIL_TIMEOUT, timeout );        mailProps.put( PROP_MAIL_CONNECTION_TIMEOUT, conntimeout );        mailProps.put( PROP_MAIL_STARTTLS, starttls ? TRUE : FALSE );        // Add SMTP authentication if required        Session session = null;        if ( useAuthentication )        {            mailProps.put( PROP_MAIL_AUTH, TRUE );            SmtpAuthenticator auth = new SmtpAuthenticator( account, password );            session = Session.getInstance( mailProps, auth );        }        else        {            session = Session.getInstance( mailProps );        }        if ( log.isDebugEnabled() )        {            String mailServer = host + ":" + port + ", account=" + account + ", password not displayed, timeout="            + timeout + ", connectiontimeout=" + conntimeout + ", starttls.enable=" + starttls            + ", use authentication=" + ( useAuthentication ? TRUE : FALSE );            log.debug( "JavaMail session obtained from standalone mail factory: " + mailServer );        }        return session;    }    /**     * Returns a JavaMail Session instance from a JNDI container-managed factory.     * @param jndiName the JNDI name for the resource. If <code>null</code>, the default value     * of <code>mail/Session</code> will be used     * @return the initialized JavaMail Session     * @throws NamingException if the Session cannot be obtained; for example, if the factory is not configured     */    protected static Session getJNDIMailSession( String jndiName ) throws NamingException    {        Session session = null;        try        {            Context initCtx = new InitialContext();            Context ctx = (Context) initCtx.lookup( JAVA_COMP_ENV );            session = (Session) ctx.lookup( jndiName );        }        catch( NamingException e )        {            log.warn( "JNDI mail session initialization error: " + e.getMessage() );            throw e;        }        if ( log.isDebugEnabled() )        {            log.debug( "mail session obtained from JNDI mail factory: " + jndiName );        }        return session;    }    /**     * Simple {@link javax.mail.Authenticator} subclass that authenticates a user to     * an SMTP server.     * @author Christoph Sauer     */    protected static class SmtpAuthenticator extends Authenticator    {        private static final String BLANK = "";        private final String m_pass;        private final String m_login;        /**         * Constructs a new SmtpAuthenticator with a supplied username and password.         * @param login the user name         * @param pass the password         */        public SmtpAuthenticator(String login, String pass)        {            super();            m_login =   login == null ? BLANK : login;            m_pass =     pass == null ? BLANK : pass;        }        /**         * Returns the password used to authenticate to the SMTP server.         * @return <code>PasswordAuthentication</code>         */        public PasswordAuthentication getPasswordAuthentication()        {            if ( BLANK.equals(m_pass) )            {                return null;            }            return new PasswordAuthentication( m_login, m_pass );        }    }}

⌨️ 快捷键说明

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