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

📄 email.java

📁 也是apache的
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements.  See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License.  You may obtain a copy of the License at * *     http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.commons.mail;import java.io.UnsupportedEncodingException;import java.nio.charset.Charset;import java.util.ArrayList;import java.util.Collection;import java.util.Date;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Properties;import javax.mail.Authenticator;import javax.mail.Message;import javax.mail.MessagingException;import javax.mail.Session;import javax.mail.Store;import javax.mail.Transport;import javax.mail.internet.AddressException;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeMultipart;import javax.naming.Context;import javax.naming.InitialContext;import javax.naming.NamingException;/** * The base class for all email messages.  This class sets the * sender's email & name, receiver's email & name, subject, and the * sent date.  Subclasses are responsible for setting the message * body. * * @since 1.0 * @author <a href="mailto:quintonm@bellsouth.net">Quinton McCombs</a> * @author <a href="mailto:jon@latchkey.com">Jon S. Stevens</a> * @author <a href="mailto:frank.kim@clearink.com">Frank Y. Kim</a> * @author <a href="mailto:bmclaugh@algx.net">Brett McLaughlin</a> * @author <a href="mailto:greg@shwoop.com">Greg Ritter</a> * @author <a href="mailto:unknown">Regis Koenig</a> * @author <a href="mailto:colin.chalmers@maxware.nl">Colin Chalmers</a> * @author <a href="mailto:matthias@wessendorf.net">Matthias Wessendorf</a> * @author <a href="mailto:corey.scott@gmail.com">Corey Scott</a> * @version $Revision: 577476 $ $Date: 2007-09-19 16:50:30 -0700 (Wed, 19 Sep 2007) $ * @version $Id: Email.java 577476 2007-09-19 23:50:30Z bspeakmon $ */public abstract class Email{    /** Constants used by Email classes. */    /** */    public static final String SENDER_EMAIL = "sender.email";    /** */    public static final String SENDER_NAME = "sender.name";    /** */    public static final String RECEIVER_EMAIL = "receiver.email";    /** */    public static final String RECEIVER_NAME = "receiver.name";    /** */    public static final String EMAIL_SUBJECT = "email.subject";    /** */    public static final String EMAIL_BODY = "email.body";    /** */    public static final String CONTENT_TYPE = "content.type";    /** */    public static final String MAIL_HOST = "mail.smtp.host";    /** */    public static final String MAIL_PORT = "mail.smtp.port";    /** */    public static final String MAIL_SMTP_FROM = "mail.smtp.from";    /** */    public static final String MAIL_SMTP_AUTH = "mail.smtp.auth";    /** */    public static final String MAIL_SMTP_USER = "mail.smtp.user";    /** */    public static final String MAIL_SMTP_PASSWORD = "mail.smtp.password";    /** */    public static final String MAIL_TRANSPORT_PROTOCOL =        "mail.transport.protocol";    /**     * @since 1.1     */    public static final String MAIL_TRANSPORT_TLS = "mail.smtp.starttls.enable";    /** */    public static final String MAIL_SMTP_SOCKET_FACTORY_FALLBACK = "mail.smtp.socketFactory.fallback";    /** */    public static final String MAIL_SMTP_SOCKET_FACTORY_CLASS = "mail.smtp.socketFactory.class";    /** */    public static final String MAIL_SMTP_SOCKET_FACTORY_PORT = "mail.smtp.socketFactory.port";    /** */    public static final String SMTP = "smtp";    /** */    public static final String TEXT_HTML = "text/html";    /** */    public static final String TEXT_PLAIN = "text/plain";    /** */    public static final String ATTACHMENTS = "attachments";    /** */    public static final String FILE_SERVER = "file.server";    /** */    public static final String MAIL_DEBUG = "mail.debug";    /** */    public static final String KOI8_R = "koi8-r";    /** */    public static final String ISO_8859_1 = "iso-8859-1";    /** */    public static final String US_ASCII = "us-ascii";    /** The email message to send. */    protected MimeMessage message;    /** The charset to use for this message */    protected String charset;    /** The Address of the sending party, mandatory */    protected InternetAddress fromAddress;    /** The Subject  */    protected String subject;    /** An attachment  */    protected MimeMultipart emailBody;    /** The content  */    protected Object content;    /** The content type  */    protected String contentType;    /** Set session debugging on or off */    protected boolean debug;    /** Sent date */    protected Date sentDate;    /**     * Instance of an <code>Authenticator</code> object that will be used     * when authentication is requested from the mail server.     */    protected Authenticator authenticator;    /**     * The hostname of the mail server with which to connect. If null will try     * to get property from system.properties. If still null, quit     */    protected String hostName;    /**     * The port number of the mail server to connect to.     * Defaults to the standard port ( 25 ).     */    protected String smtpPort = "25";    /**     * The port number of the SSL enabled SMTP server;     * defaults to the standard port, 465.     */    protected String sslSmtpPort = "465";    /** List of "to" email adresses */    protected List toList = new ArrayList();    /** List of "cc" email adresses */    protected List ccList = new ArrayList();    /** List of "bcc" email adresses */    protected List bccList = new ArrayList();    /** List of "replyTo" email adresses */    protected List replyList = new ArrayList();    /**     * Address to which undeliverable mail should be sent.     * Because this is handled by JavaMail as a String property     * in the mail session, this property is of type <code>String</code>     * rather than <code>InternetAddress</code>.     */    protected String bounceAddress;    /**     * Used to specify the mail headers.  Example:     *     * X-Mailer: Sendmail, X-Priority: 1( highest )     * or  2( high ) 3( normal ) 4( low ) and 5( lowest )     * Disposition-Notification-To: user@domain.net     */    protected Map headers = new HashMap();    /**     * Used to determine whether to use pop3 before smtp, and if so the settings.     */    protected boolean popBeforeSmtp;    /** the host name of the pop3 server */    protected String popHost;    /** the user name to log into the pop3 server */    protected String popUsername;    /** the password to log into the pop3 server */    protected String popPassword;    /** does server require TLS encryption for authentication */    protected boolean tls;    /** does the current transport use SSL encryption? */    protected boolean ssl;    /** The Session to mail with */    private Session session;    /**     * Setting to true will enable the display of debug information.     *     * @param d A boolean.     * @since 1.0     */    public void setDebug(boolean d)    {        this.debug = d;    }    /**     * Sets the userName and password if authentication is needed.  If this     * method is not used, no authentication will be performed.     * <p>     * This method will create a new instance of     * <code>DefaultAuthenticator</code> using the supplied parameters.     *     * @param userName User name for the SMTP server     * @param password password for the SMTP server     * @see DefaultAuthenticator     * @see #setAuthenticator     * @since 1.0     */    public void setAuthentication(String userName, String password)    {        this.authenticator = new DefaultAuthenticator(userName, password);        this.setAuthenticator(this.authenticator);    }    /**     * Sets the <code>Authenticator</code> to be used when authentication     * is requested from the mail server.     * <p>     * This method should be used when your outgoing mail server requires     * authentication.  Your mail server must also support RFC2554.     *     * @param newAuthenticator the <code>Authenticator</code> object.     * @see Authenticator     * @since 1.0     */    public void setAuthenticator(Authenticator newAuthenticator)    {        this.authenticator = newAuthenticator;    }    /**     * Set the charset of the message.     *     * @param newCharset A String.     * @throws java.nio.charset.IllegalCharsetNameException if the charset name is invalid     * @throws java.nio.charset.UnsupportedCharsetException if no support for the named charset     * exists in the current JVM     * @since 1.0     */    public void setCharset(String newCharset)    {        Charset set = Charset.forName(newCharset);        this.charset = set.name();    }    /**     * Set the emailBody to a MimeMultiPart     *     * @param aMimeMultipart aMimeMultipart     * @since 1.0     */    public void setContent(MimeMultipart aMimeMultipart)    {        this.emailBody = aMimeMultipart;    }    /**     * Set the content & contentType     *     * @param   aObject aObject     * @param   aContentType aContentType     * @since 1.0     */    public void setContent(Object aObject, String aContentType)    {        this.content = aObject;        if (EmailUtils.isEmpty(aContentType))        {            this.contentType = null;        }        else        {            // set the content type            this.contentType = aContentType;            // set the charset if the input was properly formed            String strMarker = "; charset=";            int charsetPos = aContentType.toLowerCase().indexOf(strMarker);            if (charsetPos != -1)            {                // find the next space (after the marker)                charsetPos += strMarker.length();                int intCharsetEnd =                    aContentType.toLowerCase().indexOf(" ", charsetPos);                if (intCharsetEnd != -1)                {                    this.charset =                        aContentType.substring(charsetPos, intCharsetEnd);                }                else                {                    this.charset = aContentType.substring(charsetPos);                }            }            else            {                // use the default charset, if one exists, for messages                // whose content-type is some form of text.                if (this.contentType.startsWith("text/") && EmailUtils.isNotEmpty(this.charset))                {                    StringBuffer contentTypeBuf = new StringBuffer(this.contentType);                    contentTypeBuf.append(strMarker);                    contentTypeBuf.append(this.charset);                    this.contentType = contentTypeBuf.toString();                }            }        }    }    /**     * Set the hostname of the outgoing mail server     *     * @param   aHostName aHostName     * @since 1.0     */    public void setHostName(String aHostName)    {        this.hostName = aHostName;    }    /**     * Set or disable the TLS encryption     *     * @param withTLS true if TLS needed, false otherwise     * @since 1.1     */    public void setTLS(boolean withTLS)    {        this.tls = withTLS;    }    /**     * Set the port number of the outgoing mail server.     * @param   aPortNumber aPortNumber     * @since 1.0     */    public void setSmtpPort(int aPortNumber)    {        if (aPortNumber < 1)        {            throw new IllegalArgumentException(                "Cannot connect to a port number that is less than 1 ( "                    + aPortNumber                    + " )");        }        this.smtpPort = Integer.toString(aPortNumber);    }    /**     * Supply a mail Session object to use     * @param aSession mail session to be used     * @since 1.0     */    public void setMailSession(Session aSession)    {        Properties sessionProperties = aSession.getProperties();        String auth = sessionProperties.getProperty(MAIL_SMTP_AUTH);        if ("true".equalsIgnoreCase(auth))        {            String userName = sessionProperties.getProperty(MAIL_SMTP_USER);            String password = sessionProperties.getProperty(MAIL_SMTP_PASSWORD);            this.authenticator = new DefaultAuthenticator(userName, password);            this.session = Session.getInstance(sessionProperties, this.authenticator);        }        else        {            this.session = aSession;        }    }    /**     * Supply a mail Session object from a JNDI directory     * @param jndiName name of JNDI ressource (javax.mail.Session type), ressource     * if searched in java:comp/env if name dont start with "java:"     * @throws IllegalArgumentException JNDI name null or empty     * @throws NamingException ressource can be retrieved from JNDI directory     * @since 1.1     */    public void setMailSessionFromJNDI(String jndiName) throws NamingException    {        if (EmailUtils.isEmpty(jndiName))        {            throw new IllegalArgumentException("JNDI name missing");        }        Context ctx = null;        if (jndiName.startsWith("java:"))        {            ctx = new InitialContext();        }        else        {            ctx = (Context) new InitialContext().lookup("java:comp/env");        }        this.setMailSession((Session) ctx.lookup(jndiName));    }    /**     * Initialise a mailsession object     *     * @return A Session.     * @throws EmailException thrown when host name was not set.     * @since 1.0

⌨️ 快捷键说明

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