如何自學JavaMail 1.4.3

解壓下載的zip文件得到一個文件夾,在文件夾根目錄下的問價結構如下:

image

首先用寫字板打開README.txt。如所有java文檔一樣,首先介紹jdk版本的問題:

JDK Version notes
-----------------

While JavaMail will work with JAF 1.0.2, we recommend the use of JAF 1.1
or newer.  JAF 1.1.1 is currently the newest version.  Note that JAF 1.1
is included in JDK 1.6 and JAF 1.1.1 is included in JDK 1.6.0_10 and
later.

注:安裝jdk1.6的用戶可以不用安裝JAF,否則需要安裝JAF。

Protocols supported
-------------------

The following table lists the names of the supported protocols (as used
in the JavaMail API) and their capabilities:

    Protocol    Store or        Uses    Supports
    Name      Transport?      SSL?    STARTTLS?
    -------------------------------------------------
    imap          Store          No          Yes
    imaps        Store          Yes         Yes
    pop3          Store          No           No
    pop3s        Store          Yes          No
    smtp        Transport       No         Yes
    smtps      Transport       Yes        Yes

注:可以看出smtp需要Transport這個類來進行通信,多組smtp是需要ssl進行驗證的,smtp需要tls認證。

Contents
--------

這裏是詳細描述文件夾目錄結構及內容的文件。重要的有如下幾個:

NOTES.txt        Notes, issues and known bugs

內容介紹:(這裏我只挑重要的說,後面也是如此)

——————————————————————————————————————————————                               

The JavaMail API jar file "mail.jar" includes the full JavaMail API
implementation and *all* the Sun protocol providers - IMAP, SMTP, and
POP3.  The simplest way to use the JavaMail API is to just use the
mail.jar file and ignore the other jar files in this package.

可以只把mail.jar引入到類庫就可以進行所有開發。

An important note when using the separate protocol provider jar files:

You can't mix and match the Sun protocol providers between different
releases of the JavaMail API. 

不能用不同版本的api。

SASL Support。此處我並不知道sasl是什麼,很簡單,去google,只是簡單瞭解下,然後我發現這個詞的解釋還是不太清楚,沒關係,忽略它,只是有個印象就行。

DSN Support。To make use of this support you need to include dsn.jar
in your CLASSPATH along with mail.jar.  See the javadocs for the
com.sun.mail.dsn package for more details.很清楚的給出了要支持DSN就要在lib中加dsn.jar,還有他的使用文檔的位置。

How to submit bug reports。介紹瞭如何提交bug和一些常見的bug的解決。比較重要的如下:

1.Your problem:    javax.mail or javax.activation classes not found when compiling.
   Our response:    You didn't set CLASSPATH correctly to find mail.jar and activation.jar.

2.Your problem:    How do I create a message with an attachment?
    Our response:    Create a message with a MimeMultipart content. See the sendfile.html and msgmultisendsample.java demo programs.

3.Your problem:Internationalization.  Parameter encoding in MIME headers, as
   specified by RFC2231, *has* been implemented.  Note that
   this covers only certain special cases not covered by the MIME
   specification.  MIME specifies encoding of text in the Subject
   and address headers, and JavaMail fully supports such encoding.
   Most mailers don't support RFC2231.

   Our response:To enable RFC2231 support in parameter lists, set the System
   properties mail.mime.encodeparameters and mail.mime.decodeparameters
   to "true".

4. We've received reports of IMAP authentication failures on the
   Microsoft Exchange Server 5.5, enterprise edition. This is due to
   a bug in the Microsoft server and the "Service Pack 1 for Exchange
   Server 5.5" apparently fixes this server bug. The service pack can
   be downloaded from the Microsoft website.(這個對我們其實不怎麼重要,因爲比較流行的郵箱都提供了smtp和pop3,我們不一定要用imap,不過既然和微軟沾邊我就順帶記下來,到時候來查究行)

5.Due to a problem in the Microsoft Exchange IMAP server, insufficient
   number of bytes may be retrieved when reading big messages. There
   are two ways to workaround this Exchange bug: (同上,微軟就是讓人不得不重視啊)

   (a) The Exchange IMAP server provides a configuration option called
       "fast message retrieval" to the UI.  Simply go to the site, server
       or recipient, click on the "IMAP4" tab, and one of the check boxes
       is "enable fast message retrieval".  Turn it off and the octet
       counts will be exact.  This is fully described at
http://support.microsoft.com/default.aspx?scid=kb;EN-US;Q191504

   (b) Set the "mail.imap.partialfetch" property to false. You'll have
       to set this property in the Properties object that you provide to
       your Session.

How to give feedback。給出瞭解決問題和反饋的具體方法,如郵件和論壇上。

——————————————————————————————————————————————

SSLNOTES.txt    Notes on using SSL/TLS with JavaMail

內容介紹 :         Notes for use of SSL with JavaMail(這裏我只挑重要的說,後面也是如此)

there are two alternative approaches to enable use of SSL.

First, and perhaps the simplest, is to set a property to enable use
of SSL.  For example, to enable use of SSL for SMTP connections, set
the property "mail.smtp.ssl.enable" to "true".

當我打開這個文檔讀到此處時,我解決了連接gmail出現“isSSL false”錯誤信息的問題。

Alternatively, you can configure JavaMail to use one of the SSL-enabled
protocol names.  In addition to the non-SSL JavaMail protocols "imap",
"pop3", and "smtp", the protocols "imaps", "pop3s", and "smtps" can
be used to connect to the corresponding services using an SSL
connection.

讀到此處我知道我可以用smtps代替smtp來解決如上問題。我用“props.setProperty("mail.transport.protocol", "smtps");”這段代碼代替了原代碼,並且沒有用第一種方法果然生效了。

-- STARTTLS support

The STARTTLS support is available in the standard "imap" and "smtp"
protocols, but must be enabled by setting the appropriate property,
mail.imap.starttls.enable or mail.smtp.starttls.enable, to "true".
When set, if the server supports the STARTTLS command, it will be
used after making the connection and before sending any login
information.

設置mail.imap.starttls.enable 或者 mail.smtp.starttls.enable爲 "true"就可以提供這種支持。

-- Server Identity Check

RFC 2595 specifies addition checks that must be performed on the
server's certificate to ensure that the server you connected to is
the server you intended to connect to.  This reduces the risk of
"man in the middle" attacks.  For compatibility with earlier releases
of JavaMail, these additional checks are disabled by default.  We
strongly recommend that you enable these checks when using SSL.  To
enable these checks, set the "mail..ssl.checkserveridentity"
property to "true".

主要是減少黑客的攻擊。

-- Socket Factories

In earlier releases it was necessary to explicitly set a socket
factory property to enable use of SSL.  In almost all cases, this
is no longer necessary.  SSL support is built in.  However, there
is one case where a special socket factory may be needed.

JavaMail now includes a special SSL socket factory that can simplify
dealing with servers with self-signed certificates.  While the
recommended approach is to include the certificate in your keystore
as described above, the following approach may be simpler in some cases.

The class com.sun.mail.util.MailSSLSocketFactory can be used as a
simple socket factory that allows trusting all hosts or a specific set
of hosts.  For example:

    MailSSLSocketFactory sf = new MailSSLSocketFactory();
    sf.setTrustAllHosts(true);
    // or
    // sf.setTrustedHosts(new String[] { "my-server" });
    props.put("mail.smtp.ssl.enable", "true");
    // also use following for additional safety
    //props.put("mail.smtp.ssl.checkserveridentity", "true");
    props.put("mail.smtp.ssl.socketFactory", sf);

Use of MailSSLSocketFactory avoids the need to add the certificate to
your keystore as described above, or configure your own TrustManager
as described below.

避免添加認證或者配置你自己的可信任管理。(解釋可能不到位,不過只要瞭解下郵箱運營就能瞭解基本意思)

-- keytool Usage

Given a certificate for the server as used in case #2 above, you can
import this certificate into your Java keystore file using a command
such as:

    keytool -import -alias imap-server -file imap.cer

The keytool command can also be used to generate a self-signed certificate
that can be used by your mail server, if you're setting up your own server.
Other utilities, such as those included with the OpenSSL package, can also
be used to generate such certificates, and they can be imported into the
Java keystore using keytool.

-- Configuring Your Own Trust Manager

When using SSL/TLS, it's important to ensure that the server you connect
to is actually the server you expected to connect to, to prevent "man in
the middle" attacks on your communication.  The recommended technique is
to configure the Java keystore using one of the methods described above.
If, for some reason, that approach is not workable, it's also possible
to configure the SSL/TLS implementation to use your own TrustManager
class to evaluate whether to trust the server you've connected to.

The following "dummy" classes illustrate the framework necessary to create
your own TrustManager implementation.

First, a replacement for the standard SSLSocketFactory is needed, to allow
you to specify which TrustManager to use:

==> DummySSLSocketFactory.java <==

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

import javax.net.SocketFactory;
import javax.net.ssl.*;

/**
* DummySSLSocketFactory
*/
public class DummySSLSocketFactory extends SSLSocketFactory {
    private SSLSocketFactory factory;

    public DummySSLSocketFactory() {
    try {
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(null,
                 new TrustManager[] { new DummyTrustManager()},
                 null);
        factory = (SSLSocketFactory)sslcontext.getSocketFactory();
    } catch(Exception ex) {
        // ignore
    }
    }

    public static SocketFactory getDefault() {
    return new DummySSLSocketFactory();
    }

    public Socket createSocket() throws IOException {
    return factory.createSocket();
    }

    public Socket createSocket(Socket socket, String s, int i, boolean flag)
                throws IOException {
    return factory.createSocket(socket, s, i, flag);
    }

    public Socket createSocket(InetAddress inaddr, int i,
                InetAddress inaddr1, int j) throws IOException {
    return factory.createSocket(inaddr, i, inaddr1, j);
    }

    public Socket createSocket(InetAddress inaddr, int i)
                throws IOException {
    return factory.createSocket(inaddr, i);
    }

    public Socket createSocket(String s, int i, InetAddress inaddr, int j)
                throws IOException {
    return factory.createSocket(s, i, inaddr, j);
    }

    public Socket createSocket(String s, int i) throws IOException {
    return factory.createSocket(s, i);
    }

    public String[] getDefaultCipherSuites() {
    return factory.getDefaultCipherSuites();
    }

    public String[] getSupportedCipherSuites() {
    return factory.getSupportedCipherSuites();
    }
}

Next you need the actual implementation of the TrustManager.  This dummy
trust manager trusts anything.  THIS IS NOT SECURE!!!

==> DummyTrustManager.java <==

import javax.net.ssl.X509TrustManager;
import java.security.cert.X509Certificate;

/**
* DummyTrustManager - NOT SECURE
*/
public class DummyTrustManager implements X509TrustManager {

    public void checkClientTrusted(X509Certificate[] cert, String authType) {
    // everything is trusted
    }

    public void checkServerTrusted(X509Certificate[] cert, String authType) {
    // everything is trusted
    }

    public X509Certificate[] getAcceptedIssuers() {
    return new X509Certificate[0];
    }
}

Finally, you need to configure JavaMail to use your SSLSocketFactory.
Set the appropriate protocol-specific property, e.g.,

    props.setProperty("mail.imap.ssl.enable", "true");
    props.setProperty("mail.imap.ssl.socketFactory.class",
                    "DummySSLSocketFactory");
    props.setProperty("mail.imap.ssl.socketFactory.fallback", "false");
    Session session = Session.getInstance(props, null);

Similar properties would need to be set to use other protocols.

教你如何添加自己的可信任管理,其實就是處理那些垃圾郵件。

——————————————————————————————————————————————

NTLMNOTES.txt 有關ntlm的相關內容(基本上用不到)。  

——————————————————————————————————————————————

javamail-1.4.3/docs/JavaMail-1.4.pdf詳細介紹了各種指令,還有properties的各種值的介紹。demo是其中例子的代碼。

——————————————————————————————————————————————

javamail-1.4.3/docs/javadocs/index.html是javamail api的起始頁,方法可以去那裏找。

——————————————————————————————————————————————

現在我們通過閱讀readme.txt知道我們最終要閱讀 JavaMail-1.4.pdf來了解編程。當我們讀完pdf後,我們就可以自如的編寫javamail了。                   

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章