Javamail-api-quick-guide

提供:Dev Guides
移動先:案内検索

JavaMail API-概要

JavaMail APIは、プラットフォームおよびプロトコルに依存しないフレームワークを提供して、メールおよびメッセージングアプリケーションを構築します。 JavaMail APIは、メールシステムを構成するオブジェクトを定義する一連の抽象クラスを提供します。 これは、電子メッセージの読み取り、作成、および送信用のオプションパッケージ(標準拡張機能)です。

JavaMailは、システムコンポーネントやインターフェイスなど、メッセージングシステムへのインターフェイスを構築するために使用される要素を提供します。 この仕様は特定の実装を定義していませんが、JavaMailにはRFC822およびMIMEインターネットメッセージング標準を実装するいくつかのクラスが含まれています。 これらのクラスは、JavaMailクラスパッケージの一部として提供されます。

JavaMail APIでサポートされているプロトコルの一部を次に示します。

  • SMTPSimple Mail Transfer Protocol の頭字語。 電子メールを配信するメカニズムを提供します。
  • POPPost Office Protocol の頭字語。 POPは、インターネット上のほとんどの人がメールを取得するために使用するメカニズムです。 各ユーザーの単一のメールボックスのサポートを定義します。 RFC 1939はこのプロトコルを定義しています。
  • IMAPInternet Message Access Protocol の頭字語。 メッセージを受信するための高度なプロトコルです。 各ユーザーに複数のメールボックスのサポートを提供し、さらに、複数のユーザーがメールボックスを共有できます。 RFC 2060で定義されています。
  • MIMEMultipurpose Internet Mail Extensions の頭字語。 。メール転送プロトコルではありません。 代わりに、転送される内容の内容、つまりメッセージの形式、添付ファイルなどを定義します。 ここで有効になる多くの異なるドキュメントがあります:RFC 822、RFC 2045、RFC 2046、およびRFC 2047。 JavaMail APIのユーザーは、通常これらの形式について心配する必要はありません。 ただし、これらの形式は存在し、プログラムで使用されます。
  • * NNTPおよびその他*:サードパーティのプロバイダーによって提供される多くのプロトコルがあります。 それらのいくつかは、ネットワークニュース転送プロトコル(NNTP)、セキュアな多目的インターネットメール拡張機能(S/MIME)などです。

これらの詳細については、以降の章で説明します。

建築

上記のように、JavaアプリケーションはJavaMail APIを使用して電子メールを作成、送信、および受信します。次の図はJavaMailのアーキテクチャを示しています。

JavaMail APIアーキテクチャ

JavaMail APIの抽象的なメカニズムは、JDBC、JNDI、JMSなどの他のJ2EE APIと似ています。 上記のアーキテクチャ図に見られるように、JavaMail APIは2つの主要な部分に分かれています。

  • アプリケーションに依存しない部分:アプリケーションコンポーネントは、アプリケーションプログラミングインターフェイス(API)を使用して、基礎となるプロバイダーや使用プロトコルに関係なく、メールメッセージを送受信します。
  • サービスに依存する部分:サービスプロバイダーインターフェイス(SPI)は、SMTP、POP、IMAP、ネットワークニュース転送プロトコル(NNTP)などのプロトコル固有の言語を話します。 電子メールサービスのプロバイダーをJ2EEプラットフォームにプラグインするために使用されます。

JavaMail API-環境設定

Javaアプリケーションを使用して電子メールを送信するのは非常に簡単ですが、最初に JavaMail API と* Java Activation Framework(JAF)*をマシンにインストールする必要があります。

'_Java SE 6以降を使用していない場合にのみ、_javax.activation_パッケージを提供する* JavaBeans Activation Framework(JAF)*拡張機能が必要になります。_

  • 最新バージョンのhttp://www.oracle.com/technetwork/java/javamail/indexl[JavaMail(Version 1.5.0)]は、Javaの標準Webサイトからダウンロードできます。
  • 最新バージョンのhttp://www.oracle.com/technetwork/java/javase/index-jsp-136939l[JAF(Version 1.1.1)]は、Javaの標準Webサイトからダウンロードできます。

これらのファイルをダウンロードして解凍すると、新しく作成された最上位ディレクトリに、両方のアプリケーションの多数のjarファイルがあります。 CLASSPATHに mail.jar および activation.jar ファイルを追加する必要があります。

SMTPサーバー

メールを送信するには、メールの送信を担当するSMTPサーバーが必要です。 以下の手法のいずれかを使用して、SMTPサーバーを取得できます。

  • Postfixサーバー(Ubuntu用)、Apache Jamesサーバー(Java Apache Mail Enterprise Server)などのSMTPサーバーをインストールして使用します。 (or)
  • たとえば、ホストプロバイダーが提供するSMTPサーバーを使用します。http://www.jangosmtp.com/[JangoSMTP]サイトが提供する無料のSMTPは_relay.jangosmtp.net_(または)です。
  • 企業が提供するSMTPサーバーを使用します。 gmail、yahooなど

'_後続の章の例では、無料のJangoSMTPサーバーを使用してメールを送信しました。 このサイトにアクセスしてアカウントを作成し、メールアドレスを設定できます。_

JavaMail API-コアクラス

JavaMail APIは、電子メールメッセージの送信、読み取り、削除に使用されるいくつかのインターフェイスとクラスで構成されています。 JavaMail APIには多くのパッケージがありますが、Java Mail APIで頻繁に使用される主な2つのパッケージ、_javax.mail_および_javax.mail.internet_パッケージについて説明します。 これらのパッケージには、すべてのJavaMailコアクラスが含まれています。 彼らです:

Class Description
javax.mail.Session The key class of the API. A multithreaded object represents the connection factory.
javax.mail.Message An abstract class that models an e-mail message. Subclasses provide the actual implementations.
javax.mail.Address An abstract class that models the addresses (from and to addresses) in a message. Subclasses provide the specific implementations.
javax.mail.Authenticator An abstract class used to protect mail resources on the mail server.
javax.mail.Transport An abstract class that models a message transport mechanism for sending an e-mail message.
javax.mail.Store An abstract class that models a message store and its access protocol, for storing and retrieving messages. A Store is divided into Folders.
javax.mail.Folder An abstract class that represents a folder of mail messages. It can contain subfolders.
javax.mail.internet.MimeMessage Message is an abstract class, hence must work with a subclass; in most cases, you’ll use a MimeMessage. A MimeMessage is an e-mail message that understands MIME types and headers.
javax.mail.internet.InternetAddress This class represents an Internet email address using the syntax of RFC822. Typical address syntax is of the form [email protected] or Personal Name <[email protected]>.

これらの各クラスを詳細に研究してみましょう。以降の章では、これらの各クラスを使用して例を学習します。

[class_session]#

セッションクラス

_Session_クラスはJavaMail APIの主要なクラスであり、サブクラス化されていません。 _Session_オブジェクトは、構成設定と認証の両方を処理するJavaMail APIの接続ファクトリーとして機能します。

_Session_オブジェクトは、次の方法で作成できます。

  • JNDIサービスに保存されている管理対象オブジェクトを検索することにより
InitialContext ctx = new InitialContext();
Session session = (Session) ctx.lookup("usersMailSession");

+ _usersMailSession_は、Sessionオブジェクトの管理対象オブジェクトとして使用されるJNDI名オブジェクトです。 _usersMailSession_は、メールサーバーのホスト名、メールを送信するユーザーアカウント、Sessionオブジェクトでサポートされるプロトコルなどの情報を含む、名前と値のペアとして必要なパラメーターを使用して作成および構成できます。 * Sessionオブジェクトを作成するもう1つの方法は、_java.util.Properties_オブジェクトを使用して、メールサーバー名、ユーザー名、パスワード、その他の情報などのデフォルト情報の一部をオーバーライドできるプログラムによるアプローチに基づいています。アプリケーション全体で共有されます。

_Session_クラスのコンストラクターは_private_です。 したがって、_Session_クラスは、_Session_オブジェクトを取得する2つのメソッド(以下にリスト)を提供します。

  • * getDefaultInstance()*:getDefaultInstance()メソッドを使用してセッションオブジェクトを取得するには、2つのメソッドがあります。 デフォルトのセッションを返します。
public static Session getDefaultInstance(Properties props)
public static Session getDefaultInstance(Properties props,Authenticator auth)
  • * getInstance()*:getInstance()メソッドを使用してセッションオブジェクトを取得するには、2つのメソッドがあります。 新しいセッションを返します。
public static Session getInstance(Properties props)
public static Session getInstance(Properties props,Authenticator auth)

[class_message]#

メッセージクラス

Sessionオブジェクトを作成したら、送信するメッセージの作成に進みます。 メッセージタイプは_javax.mail.Message_になります。

  • _Message_は抽象クラスです。 したがって、そのサブクラス_javax.mail.internet.MimeMessage_クラスが主に使用されます。
  • メッセージを作成するには、MimeMessageクラスコンストラクターでセッションオブジェクトを渡す必要があります。 例えば:
MimeMessage message=new MimeMessage(session);
  • メッセージオブジェクトが作成されたら、情報を保存する必要があります。 _Message_クラスはjavax.mail.Partインターフェースを実装し、javax.mail.internetを実装します。 MimeMessageはjavax.mail.internet.MimePartを実装します。 message.setContent()またはmimeMessage.setText()を使用してコンテンツを保存できます。
  • MimeMessageクラスの一般的に使用されるメソッドは次のとおりです。
Method Description
public void setFrom(Address address) used to set the from header field.
public void addRecipients(Message.RecipientType type, String addresses) used to add the given address to the recipient type.
public void setSubject(String subject) used to set the subject header field.
public void setText(String textmessage) used to set the text as the message content using text/plain MIME type.

[class_address]#

住所クラス

SessionおよびMessage(コンテンツが格納されている)オブジェクトが用意できたので、_Address_オブジェクトを使用してレターをアドレス指定する必要があります。

  • _Address_は抽象クラスです。 したがって、そのサブクラス_javax.mail.internet.InternetAddress_クラスが主に使用されます。
  • _Address_は、メールアドレスを渡すだけで作成できます。
Address address = new InternetAddress("[email protected]");
  • アドレスを作成するもう1つの方法は、名前alogにメールアドレスを渡すことです。
Address address = new InternetAddress("[email protected]", Manisha);
  • 以下のように、To、From、CC、BCCフィールドを設定することもできます
  • message.setFrom(アドレス)
  • message.addRecipient(type、address)
  • 3つの定義済みアドレスタイプは、次のいずれかの値を持つオブジェクトです。
  • Message.RecipientType.TO
  • Message.RecipientType.CC
  • Message.RecipientType.BCC

[class_authenticator]#

オーセンティケータークラス

クラスAuthenticatorは、ネットワーク接続の認証を取得する方法を知っているオブジェクトを表します。 通常、ユーザーに情報の入力を求めることでこれを行います。

  • _Authenticator_は抽象クラスです。 サブクラス_PasswordAuthentication_を作成し、ユーザー名とパスワードをコンストラクターに渡します。
  • セッションオブジェクトを作成するときは、AuthenticatorをSessionに登録する必要があります。

以下は、_Authenticator_の使用例です。

Properties props = new Properties();
//Override props with any customized data
PasswordAuthentication auth = new PasswordAuthentication("manisha", "pswrd")
Session session = Session.getDefaultInstance(props, auth);

[class_transport]#

輸送クラス

_Transport_クラスは、メッセージトランスポートメカニズムとして使用されます。 このクラスは通常、SMTPプロトコルを使用してメッセージを送信します。

  • これは抽象クラスです。
  • 静的な_send()_メソッドを呼び出すだけで、クラスのデフォルトバージョンを使用できます。
Transport.send(message);
  • メッセージを送信するもう1つの方法は、プロトコルのセッションから特定のインスタンスを取得し、ユーザー名とパスワード(不要な場合は空白)を渡し、メッセージを送信し、接続を閉じることです。
message.saveChanges();//implicit with send()
//Get transport for session
Transport transport = session.getTransport("smtp");
//Connect
transport.connect(host, username, password);
//repeat if necessary
transport.sendMessage(message, message.getAllRecipients());
//Done, close the connection
transport.close();

[class_store]#

店舗クラス

メッセージを保存および取得するための、メッセージストアとそのアクセスプロトコルをモデル化する抽象クラス。 サブクラスは実際の実装を提供します。 _Store_は_Service_クラスを拡張し、ストアの命名、ストアへの接続、および接続イベントのリッスンのための多くの一般的なメソッドを提供します。

クライアントは、データベースアクセスプロトコルを実装するStoreオブジェクトを取得することにより、メッセージストアにアクセスします。 ほとんどのメッセージストアでは、アクセスを許可する前にユーザーを認証する必要があります。 connectメソッドはその認証を実行します。

Store store = session.getStore("pop3");
store.connect(host, username, password);

[class_folder]#

フォルダークラス

_Folder_は、メールメッセージのフォルダーを表す抽象クラスです。 サブクラスは、プロトコル固有のフォルダーを実装します。 フォルダーにはメッセージだけでなくサブフォルダーも含めることができるため、階層構造を提供します。

ストアに接続した後、フォルダを取得できます。フォルダを開いてからメッセージを読むことができます。

Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
Message message[] = folder.getMessages();

Folderオブジェクトの_getFolder(String name)_メソッドは、名前付きサブフォルダーを返します。 メールの読み取りが完了したら、ストアとフォルダーの両方の接続を閉じます。

ストアとフォルダーの関係は次の画像で確認できます。

JavaMail APIストアとフォルダーの関係

ご覧のとおり、ユーザーアカウントごとに、サーバーにはユーザーのメッセージを保存するストアがあります。 ストアはフォルダーに分割され、「受信ボックス」フォルダーは、主に電子メールメッセージを含むフォルダーです。 フォルダーには、メッセージとサブフォルダーの両方を含めることができます。

JavaMail API-メールの送信

JavaMail APIとそのコアクラスについて公正な考えができたので、単純な電子メール、添付ファイル付き電子メール、HTMLコンテンツ付き電子メール、インライン画像付き電子メールを送信する単純なプログラムを作成しましょう。

上記のすべてのシナリオで実行される基本的な手順は次のとおりです。

  • Sessionオブジェクトを取得します。
  • メッセージを作成します。
  • メッセージを送信します。

次のセクションでは、次の簡単な例を示しました。

  • リンク:/javamail_api/javamail_api_sending_simple_email [簡単なメールを送信]
  • リンク:/javamail_api/javamail_api_send_email_with_attachment [添付ファイルをメールで送信]
  • link:/javamail_api/javamail_api_send_html_in_email [HTMLコンテンツをメールで送信]
  • link:/javamail_api/javamail_api_send_inlineimage_in_email [インライン画像をメールで送信]

JavaMail API-メールの確認

この章に進む前に、理解する必要がある2つの側面があります。 CheckFetch です。

  • JavaMailでのチェックは、メールボックス内の各フォルダーを開いて各メッセージを取得するプロセスです。 ここでは、各メッセージのヘッダー、つまり_From、To、subject_のみを確認します。 コンテンツは読み込まれません。
  • JavaMailでメールをフェッチすることは、メールボックス内のそれぞれのフォルダーを開いて各メッセージを取得するプロセスです。 ヘッダーとともに、コンテンツタイプを認識することでコンテンツを読み取ります。

JavaMail APIを使用してメールを確認または取得するには、POPまたはIMAPサーバーが必要です。 メールを確認して取得するには、FolderクラスとStoreクラスが必要です。 ここでは、GMAILのPOP3サーバー(pop.gmail.com)を使用しました。 この章では、JavaMail APIを使用してメールをチェックする方法を学習します。 取得については、以降の章で説明します。 メールを確認するには:

  • セッションを取得する
  • pop3 Storeオブジェクトを作成し、popサーバーに接続します。
  • フォルダーオブジェクトを作成します。 メールボックスで適切なフォルダーを開きます。
  • メッセージを取得します。
  • StoreおよびFolderオブジェクトを閉じます。

Javaクラスを作成する

Javaクラスファイル CheckingMails を作成します。その内容は次のとおりです。

package com.finddevguides;

import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;

public class CheckingMails {

   public static void check(String host, String storeType, String user,
      String password)
   {
      try {

     //create properties field
      Properties properties = new Properties();

      properties.put("mail.pop3.host", host);
      properties.put("mail.pop3.port", "995");
      properties.put("mail.pop3.starttls.enable", "true");
      Session emailSession = Session.getDefaultInstance(properties);

     //create the POP3 store object and connect with the pop server
      Store store = emailSession.getStore("pop3s");

      store.connect(host, user, password);

     //create the folder object and open it
      Folder emailFolder = store.getFolder("INBOX");
      emailFolder.open(Folder.READ_ONLY);

     //retrieve the messages from the folder in an array and print it
      Message[] messages = emailFolder.getMessages();
      System.out.println("messages.length---" + messages.length);

      for (int i = 0, n = messages.length; i < n; i++) {
         Message message = messages[i];
         System.out.println("---------------------------------");
         System.out.println("Email Number " + (i + 1));
         System.out.println("Subject: " + message.getSubject());
         System.out.println("From: " + message.getFrom()[0]);
         System.out.println("Text: " + message.getContent().toString());

      }

     //close the store and folder objects
      emailFolder.close(false);
      store.close();

      } catch (NoSuchProviderException e) {
         e.printStackTrace();
      } catch (MessagingException e) {
         e.printStackTrace();
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   public static void main(String[] args) {

      String host = "pop.gmail.com";//change accordingly
      String mailStoreType = "pop3";
      String username = "[email protected]";//change accordingly
      String password = "*****";//change accordingly

      check(host, mailStoreType, username, password);

   }

}

コンパイルして実行する

クラスの準備ができたので、上記のクラスをコンパイルしましょう。 クラスCheckingMails.javaをディレクトリ /home/manisha/JavaMailAPIExercise に保存しました。 クラスパスに_javax.mail.jar_および_activation.jar_のjarが必要です。 以下のコマンドを実行して、コマンドプロンプトからクラス(両方のjarが/home/manisha/ディレクトリに配置されます)をコンパイルします。

javac -cp/home/manisha/activation.jar:/home/manisha/javax.mail.jar: CheckingMails.java

クラスがコンパイルされたので、次のコマンドを実行して実行します。

java -cp/home/manisha/activation.jar:/home/manisha/javax.mail.jar: CheckingMails

出力を検証する

コマンドコンソールに次のメッセージが表示されます。

messages.length---4
---------------------------------
Email Number 1
Subject: Test Mail--Fetch
From: <[email protected]>
Text: javax.mail.internet.MimeMultipart@327a5b7f
---------------------------------
Email Number 2
Subject: testing ----checking simple email
From: <[email protected]>
Text: javax.mail.internet.MimeMultipart@7f0d08bc
---------------------------------
Email Number 3
Subject: Email with attachment
From: <[email protected]>
Text: javax.mail.internet.MimeMultipart@30b8afce
---------------------------------
Email Number 4
Subject: Email with Inline image
From: <[email protected]>
Text: javax.mail.internet.MimeMultipart@2d1e165f

ここでは、INBOX内のメッセージの数(この場合は4)を出力しました。 各電子メールメッセージの件名、差出人アドレス、およびテキストも印刷しました。

JavaMail API-メールの取得

前の章では、メールをチェックする方法を学びました。 次に、各電子メールを取得してその内容を読み取る方法を見てみましょう。 次のタイプのメールを読み取るJavaクラス FetchingEmail を作成しましょう。

  • シンプルなメール
  • 添付ファイル付きメール
  • インライン画像付きメール

コードで実行される基本的な手順は次のとおりです。

  • Sessionオブジェクトを取得します。
  • POP3ストアオブジェクトを作成し、ストアに接続します。
  • Folderオブジェクトを作成し、メールボックス内の適切なフォルダーを開きます。
  • メッセージを取得します。
  • フォルダーを閉じて、それぞれオブジェクトを保存します。

Javaクラスを作成する

Javaを作成するJavaクラスファイル FetchingEmail を作成します。その内容は以下のとおりです。

package com.finddevguides;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;

public class FetchingEmail {

   public static void fetch(String pop3Host, String storeType, String user,
      String password) {
      try {
        //create properties field
         Properties properties = new Properties();
         properties.put("mail.store.protocol", "pop3");
         properties.put("mail.pop3.host", pop3Host);
         properties.put("mail.pop3.port", "995");
         properties.put("mail.pop3.starttls.enable", "true");
         Session emailSession = Session.getDefaultInstance(properties);
        //emailSession.setDebug(true);

        //create the POP3 store object and connect with the pop server
         Store store = emailSession.getStore("pop3s");

         store.connect(pop3Host, user, password);

        //create the folder object and open it
         Folder emailFolder = store.getFolder("INBOX");
         emailFolder.open(Folder.READ_ONLY);

         BufferedReader reader = new BufferedReader(new InputStreamReader(
          System.in));

        //retrieve the messages from the folder in an array and print it
         Message[] messages = emailFolder.getMessages();
         System.out.println("messages.length---" + messages.length);

         for (int i = 0; i < messages.length; i++) {
            Message message = messages[i];
            System.out.println("---------------------------------");
            writePart(message);
            String line = reader.readLine();
            if ("YES".equals(line)) {
               message.writeTo(System.out);
            } else if ("QUIT".equals(line)) {
               break;
            }
         }

        //close the store and folder objects
         emailFolder.close(false);
         store.close();

      } catch (NoSuchProviderException e) {
         e.printStackTrace();
      } catch (MessagingException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
   public static void main(String[] args) {

      String host = "pop.gmail.com";//change accordingly
      String mailStoreType = "pop3";
      String username =
         "[email protected]";//change accordingly
      String password = "*****";//change accordingly

     //Call method fetch
      fetch(host, mailStoreType, username, password);

   }

  /*
 *This method checks for content-type
  * based on which, it processes and
 *fetches the content of the message
  */
   public static void writePart(Part p) throws Exception {
      if (p instanceof Message)
        //Call methos writeEnvelope
         writeEnvelope((Message) p);

      System.out.println("----------------------------");
      System.out.println("CONTENT-TYPE: " + p.getContentType());

     //check if the content is plain text
      if (p.isMimeType("text/plain")) {
         System.out.println("This is plain text");
         System.out.println("---------------------------");
         System.out.println((String) p.getContent());
      }
     //check if the content has attachment
      else if (p.isMimeType("multipart/*")) {
         System.out.println("This is a Multipart");
         System.out.println("---------------------------");
         Multipart mp = (Multipart) p.getContent();
         int count = mp.getCount();
         for (int i = 0; i < count; i++)
            writePart(mp.getBodyPart(i));
      }
     //check if the content is a nested message
      else if (p.isMimeType("message/rfc822")) {
         System.out.println("This is a Nested Message");
         System.out.println("---------------------------");
         writePart((Part) p.getContent());
      }
     //check if the content is an inline image
      else if (p.isMimeType("image/jpeg")) {
         System.out.println("--------> image/jpeg");
         Object o = p.getContent();

         InputStream x = (InputStream) o;
        //Construct the required byte array
         System.out.println("x.length = " + x.available());
         while ((i = (int) ((InputStream) x).available()) > 0) {
            int result = (int) (((InputStream) x).read(bArray));
            if (result == -1)
         int i = 0;
         byte[] bArray = new byte[x.available()];

            break;
         }
         FileOutputStream f2 = new FileOutputStream("/tmp/image.jpg");
         f2.write(bArray);
      }
      else if (p.getContentType().contains("image/")) {
         System.out.println("content type" + p.getContentType());
         File f = new File("image" + new Date().getTime() + ".jpg");
         DataOutputStream output = new DataOutputStream(
            new BufferedOutputStream(new FileOutputStream(f)));
            com.sun.mail.util.BASE64DecoderStream test =
                 (com.sun.mail.util.BASE64DecoderStream) p
                  .getContent();
         byte[] buffer = new byte[1024];
         int bytesRead;
         while ((bytesRead = test.read(buffer)) != -1) {
            output.write(buffer, 0, bytesRead);
         }
      }
      else {
         Object o = p.getContent();
         if (o instanceof String) {
            System.out.println("This is a string");
            System.out.println("---------------------------");
            System.out.println((String) o);
         }
         else if (o instanceof InputStream) {
            System.out.println("This is just an input stream");
            System.out.println("---------------------------");
            InputStream is = (InputStream) o;
            is = (InputStream) o;
            int c;
            while ((c = is.read()) != -1)
               System.out.write(c);
         }
         else {
            System.out.println("This is an unknown type");
            System.out.println("---------------------------");
            System.out.println(o.toString());
         }
      }

   }
  /*
 *This method would print FROM,TO and SUBJECT of the message
  */
   public static void writeEnvelope(Message m) throws Exception {
      System.out.println("This is the message envelope");
      System.out.println("---------------------------");
      Address[] a;

     //FROM
      if ((a = m.getFrom()) != null) {
         for (int j = 0; j < a.length; j++)
         System.out.println("FROM: " + a[j].toString());
      }

     //TO
      if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
         for (int j = 0; j < a.length; j++)
         System.out.println("TO: " + a[j].toString());
      }

     //SUBJECT
      if (m.getSubject() != null)
         System.out.println("SUBJECT: " + m.getSubject());

   }

}

'_ステートメント_emailSession.setDebug(true); _のコメントを外すことで、デバッグをオンに設定できます。_

コンパイルして実行する

クラスの準備ができたので、上記のクラスをコンパイルしましょう。 クラスFetchingEmail.javaをディレクトリ /home/manisha/JavaMailAPIExercise に保存しました。 クラスパスに_javax.mail.jar_および_activation.jar_のjarが必要です。 以下のコマンドを実行して、コマンドプロンプトからクラス(両方のjarが/home/manisha/ディレクトリに配置されます)をコンパイルします。

javac -cp/home/manisha/activation.jar:/home/manisha/javax.mail.jar: FetchingEmail.java

クラスがコンパイルされたので、次のコマンドを実行して実行します。

java -cp/home/manisha/activation.jar:/home/manisha/javax.mail.jar: FetchingEmail

出力を検証する

コマンドコンソールに次のメッセージが表示されます。

messages.length---3
---------------------------------
This is the message envelope
---------------------------
FROM: XYZ <[email protected]>
TO: ABC <[email protected]>
SUBJECT: Simple Message
----------------------------
CONTENT-TYPE: multipart/alternative; boundary=047d7b343d6ad3e4ea04e8ec6579
This is a Multipart
---------------------------

----------------------------
CONTENT-TYPE: text/plain; charset=ISO-8859-1
This is plain text
---------------------------
Hi am a simple message string....

--
Regards
xyz

This is the message envelope
---------------------------
FROM: XYZ <[email protected]>
TO: ABC <[email protected]>
SUBJECT: Attachement
----------------------------
CONTENT-TYPE: multipart/mixed; boundary=047d7b343d6a99180904e8ec6751
This is a Multipart
---------------------------

----------------------------
CONTENT-TYPE: text/plain; charset=ISO-8859-1
This is plain text
---------------------------
Hi I've an attachment.Please check

--
Regards
XYZ

----------------------------
CONTENT-TYPE: application/octet-stream; name=sample_attachement
This is just an input stream
---------------------------
Submit your Tutorials, White Papers and Articles into our Tutorials Directory. This is a tutorials database where we are keeping all the tutorials shared by the internet community for the benefit of others.


This is the message envelope
---------------------------
FROM: XYZ <[email protected]>
TO: ABC <[email protected]>
SUBJECT: Inline Image
----------------------------
CONTENT-TYPE: multipart/related; boundary=f46d04182582be803504e8ece94b
This is a Multipart
---------------------------

----------------------------
CONTENT-TYPE: text/plain; charset=ISO-8859-1
This is plain text
---------------------------
Hi I've an inline image


[image: Inline image 3]

--
Regards
XYZ

----------------------------
CONTENT-TYPE: image/png; name="javamail-mini-logo.png"
content typeimage/png; name="javamail-mini-logo.png"

ここで、メールボックスに3つのメールがあることを確認できます。 最初に、メッセージ「Hi am a simple message string …​.」を含む単純なメール。 2番目のメールには添付ファイルがあります。 添付ファイルの内容も上記のように印刷されます。 3番目のメールにはインライン画像があります。

JavaMail API-認証

前の章のlink:/javamail_api/javamail_api_checking_emails [Checking Emails]およびlink:/javamail_api/javamail_api_fetching_emails [Fetching Emails]では、メールボックスのストアに接続するときに、ホストとともに認証情報(ユーザー広告パスワード)を渡しました。 代わりに、ホストを持つように_Properties_を設定し、カスタムAuthenticatorインスタンスについてセッションに伝えることができます。 これを以下の例に示します。

Javaクラスを作成する

次の章のリンクからCheckingMails.javaを変更します:/javamail_api/javamail_api_checking_emails [Checking Emails]。 その内容は以下のとおりです。

package com.finddevguides;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;

public class CheckingMails {

   public static void check(String host, String storeType, String user,
      String password)
   {
      try {

     //create properties field
      Properties properties = new Properties();

      properties.put("mail.pop3s.host", host);
      properties.put("mail.pop3s.port", "995");
      properties.put("mail.pop3s.starttls.enable", "true");

     //Setup authentication, get session
      Session emailSession = Session.getInstance(properties,
         new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
               return new PasswordAuthentication(
                  "[email protected]", "manisha123");
            }
         });
     //emailSession.setDebug(true);

     //create the POP3 store object and connect with the pop server
      Store store = emailSession.getStore("pop3s");

      store.connect();

     //create the folder object and open it
      Folder emailFolder = store.getFolder("INBOX");
      emailFolder.open(Folder.READ_ONLY);

     //retrieve the messages from the folder in an array and print it
      Message[] messages = emailFolder.getMessages();
      System.out.println("messages.length---" + messages.length);

      for (int i = 0, n = messages.length; i < n; i++) {
         Message message = messages[i];
         System.out.println("---------------------------------");
         System.out.println("Email Number " + (i + 1));
         System.out.println("Subject: " + message.getSubject());
         System.out.println("From: " + message.getFrom()[0]);
         System.out.println("Text: " + message.getContent().toString());
      }

     //close the store and folder objects
      emailFolder.close(false);
      store.close();

      } catch (NoSuchProviderException e) {
         e.printStackTrace();
      } catch (MessagingException e) {
         e.printStackTrace();
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   public static void main(String[] args) {

      String host = "pop.gmail.com";//change accordingly
      String mailStoreType = "pop3";
      String username = "[email protected]";//change accordingly
      String password = "*****";//change accordingly

      check(host, mailStoreType, username, password);

   }

}

'_ステートメント_emailSession.setDebug(true); _のコメントを外すことで、デバッグをオンに設定できます。_

コンパイルして実行する

クラスの準備ができたので、上記のクラスをコンパイルしましょう。 クラスCheckingMails.javaをディレクトリ /home/manisha/JavaMailAPIExercise に保存しました。 クラスパスに_javax.mail.jar_および_activation.jar_のjarが必要です。 以下のコマンドを実行して、コマンドプロンプトからクラス(両方のjarが/home/manisha/ディレクトリに配置されます)をコンパイルします。

javac -cp/home/manisha/activation.jar:/home/manisha/javax.mail.jar: CheckingMails.java

クラスがコンパイルされたので、次のコマンドを実行して実行します。

java -cp/home/manisha/activation.jar:/home/manisha/javax.mail.jar: CheckingMails

出力を検証する

コマンドコンソールに次のようなメッセージが表示されます。

messages.length---3
---------------------------------
Email Number 1
Subject: Today is a nice day
From: XYZ <[email protected]>
Text: javax.mail.internet.MimeMultipart@45f676cb
---------------------------------
Email Number 2
Subject: hiiii....
From: XYZ <[email protected]>
Text: javax.mail.internet.MimeMultipart@37f12d4f
---------------------------------
Email Number 3
Subject: helloo
From: XYZ <[email protected]>
Text: javax.mail.internet.MimeMultipart@3ad5ba3a

JavaMail API-メールの返信

この章では、JavaMail APIを使用して電子メールに返信する方法を説明します。 以下のプログラムで実行される基本的な手順は次のとおりです。

  • プロパティでPOPおよびSMPTサーバーの詳細を含むSessionオブジェクトを取得します。 メッセージを取得するにはPOPの詳細が、メッセージを送信するにはSMPTの詳細が必要です。
  • POP3ストアオブジェクトを作成し、ストアに接続します。
  • Folderオブジェクトを作成し、メールボックス内の適切なフォルダーを開きます。
  • メッセージを取得します。
  • メッセージを繰り返し処理し、返信する場合は「Y」または「y」と入力します。
  • メッセージのすべての情報(To、From、Subject、Content)を取得します。
  • Message.reply()メソッドを使用して、返信メッセージを作成します。 このメソッドは、適切な受信者と件名で新しいメッセージを構成します。 このメソッドは、送信者のみに返信するか(false)、全員に返信するか(true)を示すブール値パラメーターを取ります。
  • メッセージにFrom、Text、およびReply-toを設定し、Transportオブジェクトのインスタンスを介して送信します。
  • Transport、folder、およびstoreオブジェクトをそれぞれ閉じます。

'_ここでは、JangoSMPTサーバーを使用して、宛先メールアドレスにメールを送信しています。 設定については、リンク:/javamail_api/javamail_api_environment_setup [Environment Setup]の章で説明しています。_

Javaクラスを作成する

Javaクラスファイル ReplyToEmail を作成します。その内容は次のとおりです。

package com.finddevguides;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class ReplyToEmail {
   public static void main(String args[])
   {
      Date date = null;

      Properties properties = new Properties();
      properties.put("mail.store.protocol", "pop3");
      properties.put("mail.pop3s.host", "pop.gmail.com");
      properties.put("mail.pop3s.port", "995");
      properties.put("mail.pop3.starttls.enable", "true");
      properties.put("mail.smtp.auth", "true");
      properties.put("mail.smtp.starttls.enable", "true");
      properties.put("mail.smtp.host", "relay.jangosmtp.net");
      properties.put("mail.smtp.port", "25");
      Session session = Session.getDefaultInstance(properties);

     //session.setDebug(true);
      try
      {
        //Get a Store object and connect to the current host
         Store store = session.getStore("pop3s");
         store.connect("pop.gmail.com", "[email protected]",
            "*****");//change the user and password accordingly

         Folder folder = store.getFolder("inbox");
         if (!folder.exists()) {
            System.out.println("inbox not found");
               System.exit(0);
         }
         folder.open(Folder.READ_ONLY);

         BufferedReader reader = new BufferedReader(new InputStreamReader(
            System.in));

         Message[] messages = folder.getMessages();
         if (messages.length != 0) {

            for (int i = 0, n = messages.length; i < n; i++) {
               Message message = messages[i];
               date = message.getSentDate();
              //Get all the information from the message
               String from = InternetAddress.toString(message.getFrom());
               if (from != null) {
                  System.out.println("From: " + from);
               }
               String replyTo = InternetAddress.toString(message
             .getReplyTo());
               if (replyTo != null) {
                  System.out.println("Reply-to: " + replyTo);
               }
               String to = InternetAddress.toString(message
             .getRecipients(Message.RecipientType.TO));
               if (to != null) {
                  System.out.println("To: " + to);
               }

               String subject = message.getSubject();
               if (subject != null) {
                  System.out.println("Subject: " + subject);
               }
               Date sent = message.getSentDate();
               if (sent != null) {
                  System.out.println("Sent: " + sent);
               }

               System.out.print("Do you want to reply [y/n] : ");
               String ans = reader.readLine();
               if ("Y".equals(ans) || "y".equals(ans)) {

                  Message replyMessage = new MimeMessage(session);
                  replyMessage = (MimeMessage) message.reply(false);
                  replyMessage.setFrom(new InternetAddress(to));
                  replyMessage.setText("Thanks");
                  replyMessage.setReplyTo(message.getReplyTo());

                 //Send the message by authenticating the SMTP server
                 //Create a Transport instance and call the sendMessage
                  Transport t = session.getTransport("smtp");
                  try {
            //connect to the smpt server using transport instance
            //change the user and password accordingly
                 t.connect("abc", "****");
                 t.sendMessage(replyMessage,
                        replyMessage.getAllRecipients());
                  } finally {
                     t.close();
                  }
                  System.out.println("message replied successfully ....");

                 //close the store and folder objects
                  folder.close(false);
                  store.close();

               } else if ("n".equals(ans)) {
                  break;
               }
            }//end of for loop

         } else {
            System.out.println("There is no msg....");
         }

      } catch (Exception e) {
         e.printStackTrace();
      }

   }

}

'_ステートメント_session.setDebug(true); _のコメントを外すことで、デバッグをオンに設定できます。_

コンパイルして実行する

クラスの準備ができたので、上記のクラスをコンパイルしましょう。 クラスReplyToEmail.javaをディレクトリ /home/manisha/JavaMailAPIExercise に保存しました。 クラスパスに_javax.mail.jar_および_activation.jar_のjarが必要です。 以下のコマンドを実行して、コマンドプロンプトからクラス(両方のjarが/home/manisha/ディレクトリに配置されます)をコンパイルします。

javac -cp/home/manisha/activation.jar:/home/manisha/javax.mail.jar: ReplyToEmail.java

クラスがコンパイルされたので、次のコマンドを実行して実行します。

java -cp/home/manisha/activation.jar:/home/manisha/javax.mail.jar: ReplyToEmail

出力を検証する

コマンドコンソールに次のメッセージが表示されます。

From: ABC <[email protected]>
Reply-to: [email protected]
To: XYZ <[email protected]>
Subject: Hi today is a nice day
Sent: Thu Oct 17 15:58:37 IST 2013
Do you want to reply [y/n] : y
message replied successfully ....

メールの送信先の受信トレイを確認します。 この場合、受信したメッセージは次のようになります。

JavaMail API返信メール

JavaMail API-メールの転送

この章では、JavaMail APIを使用して電子メールを転送する方法について説明します。 以下のプログラムで実行される基本的な手順は次のとおりです。

  • プロパティでPOPおよびSMPTサーバーの詳細を含むSessionオブジェクトを取得します。 メッセージを取得するにはPOPの詳細が、メッセージを送信するにはSMPTの詳細が必要です。
  • POP3ストアオブジェクトを作成し、ストアに接続します。
  • Folderオブジェクトを作成し、メールボックス内の適切なフォルダーを開きます。
  • メッセージを取得します。
  • メッセージを繰り返し処理し、転送する場合は「Y」または「y」と入力します。
  • メッセージのすべての情報(To、From、Subject、Content)を取得します。
  • メッセージを構成する部分を操作して、転送メッセージを作成します。 最初の部分はメッセージのテキストで、2番目の部分は転送するメッセージです。 2つを組み合わせてマルチパートにします。 次に、適切にアドレス指定されたメッセージにマルチパートを追加して送信します。
  • Transport、folder、およびstoreオブジェクトをそれぞれ閉じます。

'_ここでは、JangoSMPTサーバーを使用して、宛先メールアドレスにメールを送信しています。 設定については、リンク:/javamail_api/javamail_api_environment_setup [Environment Setup]の章で説明しています。_

Javaクラスを作成する

Javaクラスファイル ForwardEmail を作成します。その内容は次のとおりです。

package com.finddevguides;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class ForwardEmail {

   public static void main(String[] args) {
      Properties properties = new Properties();
      properties.put("mail.store.protocol", "pop3");
      properties.put("mail.pop3s.host", "pop.gmail.com");
      properties.put("mail.pop3s.port", "995");
      properties.put("mail.pop3.starttls.enable", "true");
      properties.put("mail.smtp.auth", "true");
      properties.put("mail.smtp.host", "relay.jangosmtp.net");
      properties.put("mail.smtp.port", "25");
      Session session = Session.getDefaultInstance(properties);
      try {
        //session.setDebug(true);
        //Get a Store object and connect to the current host
         Store store = session.getStore("pop3s");
         store.connect("pop.gmail.com", "[email protected]",
            "*****");//change the user and password accordingly

        //Create a Folder object and open the folder
         Folder folder = store.getFolder("inbox");
         folder.open(Folder.READ_ONLY);
         BufferedReader reader = new BufferedReader(new InputStreamReader(
            System.in));
         Message[] messages = folder.getMessages();
         if (messages.length != 0) {

         for (int i = 0, n = messages.length; i < n; i++) {
            Message message = messages[i];
           //Get all the information from the message
            String from = InternetAddress.toString(message.getFrom());
            if (from != null) {
               System.out.println("From: " + from);
            }
            String replyTo = InternetAddress.toString(message
               .getReplyTo());
            if (replyTo != null) {
               System.out.println("Reply-to: " + replyTo);
            }
            String to = InternetAddress.toString(message
               .getRecipients(Message.RecipientType.TO));
            if (to != null) {
               System.out.println("To: " + to);
            }

            String subject = message.getSubject();
            if (subject != null) {
               System.out.println("Subject: " + subject);
            }
            Date sent = message.getSentDate();
            if (sent != null) {
               System.out.println("Sent: " + sent);
            }
            System.out.print("Do you want to reply [y/n] : ");
            String ans = reader.readLine();
            if ("Y".equals(ans) || "y".equals(ans)) {
               Message forward = new MimeMessage(session);
              //Fill in header
               forward.setRecipients(Message.RecipientType.TO,
               InternetAddress.parse(from));
               forward.setSubject("Fwd: " + message.getSubject());
               forward.setFrom(new InternetAddress(to));

              //Create the message part
               MimeBodyPart messageBodyPart = new MimeBodyPart();
              //Create a multipart message
               Multipart multipart = new MimeMultipart();
              //set content
               messageBodyPart.setContent(message, "message/rfc822");
              //Add part to multi part
               multipart.addBodyPart(messageBodyPart);
              //Associate multi-part with message
               forward.setContent(multipart);
               forward.saveChanges();

              //Send the message by authenticating the SMTP server
              //Create a Transport instance and call the sendMessage
               Transport t = session.getTransport("smtp");
               try {
                 //connect to the smpt server using transport instance
         //change the user and password accordingly
                  t.connect("abc", "*****");
                  t.sendMessage(forward, forward.getAllRecipients());
               } finally {
                  t.close();
               }

               System.out.println("message forwarded successfully....");

           //close the store and folder objects
            folder.close(false);
            store.close();
            }//end if

         }//end for
   }//end if
   } catch (Exception e) {
      e.printStackTrace();
   }
}

}

'_ステートメント_session.setDebug(true); _のコメントを外すことで、デバッグをオンに設定できます。_

コンパイルして実行する

クラスの準備ができたので、上記のクラスをコンパイルしましょう。 クラスForwardEmail.javaをディレクトリ /home/manisha/JavaMailAPIExercise に保存しました。 クラスパスに_javax.mail.jar_および_activation.jar_のjarが必要です。 以下のコマンドを実行して、コマンドプロンプトからクラス(両方のjarが/home/manisha/ディレクトリに配置されます)をコンパイルします。

javac -cp/home/manisha/activation.jar:/home/manisha/javax.mail.jar: ForwardEmail.java

クラスがコンパイルされたので、次のコマンドを実行して実行します。

java -cp/home/manisha/activation.jar:/home/manisha/javax.mail.jar: ForwardEmail

出力を検証する

コマンドコンソールに次のメッセージが表示されます。

From: ABC <[email protected]>
Reply-to: [email protected]
To: XYZ <[email protected]>
Subject: Hi today is a nice day
Sent: Thu Oct 17 15:58:37 IST 2013
Do you want to reply [y/n] : y
message forwarded successfully....

メールの送信先の受信トレイを確認します。 この場合、転送されるメッセージは次のようになります。

画像:/javamail_api/images/fwdmsg_header.jpg [JavaMail API転送メール]画像:/javamail_api/images/fwdmsg_body.jpg [JavaMail API転送メール]

JavaMail API-メールの削除

この章では、JavaMail APIを使用して電子メールを削除する方法を説明します。 メッセージの削除には、メッセージに関連付けられたフラグの操作が含まれます。 状態ごとに異なるフラグがあり、システム定義のものとユーザー定義のものがあります。 定義済みのフラグは、内部クラスFlags.Flagで定義されており、以下にリストされています。

  • Flags.Flag.ANSWERED
  • Flags.Flag.DELETED
  • Flags.Flag.DRAFT
  • Flags.Flag.FLAGGED
  • Flags.Flag.RECENT
  • Flags.Flag.SEEN
  • Flags.Flag.USER

POPプロトコルは、メッセージの削除のみをサポートします。

削除プログラムで実行される基本的な手順は次のとおりです。

  • プロパティでPOPおよびSMPTサーバーの詳細を含むSessionオブジェクトを取得します。 メッセージを取得するにはPOPの詳細が、メッセージを送信するにはSMPTの詳細が必要です。
  • POP3ストアオブジェクトを作成し、ストアに接続します。
  • Folderオブジェクトを作成し、READ_WRITEモードでメールボックスの適切なフォルダーを開きます。
  • 受信トレイフォルダーからメッセージを取得します。
  • メッセージを繰り返し処理し、MessageオブジェクトでメソッドsetFlag(Flags.Flag.DELETED、true)を呼び出してメッセージを削除する場合は「Y」または「y」を入力します。
  • DELETEDとマークされたメッセージは、Folderオブジェクトでexpunge()メソッドを呼び出すか、expungeをtrueに設定してフォルダーを閉じるまで、実際には削除されません。
  • ストアオブジェクトを閉じます。

Javaクラスを作成する

Javaクラスファイル ForwardEmail を作成します。その内容は次のとおりです。

package com.finddevguides;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;

public class DeleteEmail {

   public static void delete(String pop3Host, String storeType, String user,
      String password)
   {
      try
      {
        //get the session object
         Properties properties = new Properties();
         properties.put("mail.store.protocol", "pop3");
         properties.put("mail.pop3s.host", pop3Host);
         properties.put("mail.pop3s.port", "995");
         properties.put("mail.pop3.starttls.enable", "true");
         Session emailSession = Session.getDefaultInstance(properties);
        //emailSession.setDebug(true);

        //create the POP3 store object and connect with the pop server
         Store store = emailSession.getStore("pop3s");

         store.connect(pop3Host, user, password);

        //create the folder object and open it
         Folder emailFolder = store.getFolder("INBOX");
         emailFolder.open(Folder.READ_WRITE);

         BufferedReader reader = new BufferedReader(new InputStreamReader(
            System.in));
        //retrieve the messages from the folder in an array and print it
         Message[] messages = emailFolder.getMessages();
         System.out.println("messages.length---" + messages.length);
         for (int i = 0; i < messages.length; i++) {
            Message message = messages[i];
            System.out.println("---------------------------------");
            System.out.println("Email Number " + (i + 1));
            System.out.println("Subject: " + message.getSubject());
            System.out.println("From: " + message.getFrom()[0]);

            String subject = message.getSubject();
            System.out.print("Do you want to delete this message [y/n] ? ");
            String ans = reader.readLine();
            if ("Y".equals(ans) || "y".equals(ans)) {
          //set the DELETE flag to true
           message.setFlag(Flags.Flag.DELETED, true);
           System.out.println("Marked DELETE for message: " + subject);
            } else if ("n".equals(ans)) {
           break;
            }
         }
        //expunges the folder to remove messages which are marked deleted
         emailFolder.close(true);
         store.close();

      } catch (NoSuchProviderException e) {
         e.printStackTrace();
      } catch (MessagingException e) {
         e.printStackTrace();
      } catch (IOException io) {
         io.printStackTrace();
      }
   }

   public static void main(String[] args) {

      String host = "pop.gmail.com";//change accordingly
      String mailStoreType = "pop3";
      String username = "[email protected]";//change accordingly
      String password = "*****";//change accordingly

      delete(host, mailStoreType, username, password);

   }

}

'_ステートメント_emailSession.setDebug(true); _のコメントを外すことで、デバッグをオンに設定できます。_

コンパイルして実行する

クラスの準備ができたので、上記のクラスをコンパイルしましょう。 クラスDeleteEmail.javaをディレクトリ /home/manisha/JavaMailAPIExercise に保存しました。 クラスパスに_javax.mail.jar_および_activation.jar_のjarが必要です。 以下のコマンドを実行して、コマンドプロンプトからクラス(両方のjarが/home/manisha/ディレクトリに配置されます)をコンパイルします。

javac -cp/home/manisha/activation.jar:/home/manisha/javax.mail.jar: DeleteEmail.java

クラスがコンパイルされたので、次のコマンドを実行して実行します。

java -cp/home/manisha/activation.jar:/home/manisha/javax.mail.jar: DeleteEmail

出力を検証する

コマンドコンソールに次のメッセージが表示されます。

messages.length---1
---------------------------------
Email Number 1
Subject: Testing
From: ABC <[email protected]>
Do you want to delete this message [y/n] ? y
Marked DELETE for message: Testing

JavaMail API-Gmail SMTPサーバー

前のすべての章では、JangoSMTPサーバーを使用してメールを送信しました。 この章では、Gmailが提供するSMTPサーバーについて学びます。 Gmail(特に)は、パブリックSMTPサーバーの使用を無料で提供しています。

Gmail SMTPサーバーの詳細は、https://support.google.com/mail/answer/13287?hl = ja [こちら]で確認できます。 詳細でわかるように、TLSまたはSSL接続を使用して、Gmail SMTPサーバー経由でメールを送信できます。

Gmail SMTPサーバーを使用してメールを送信する手順は、リンクの章:/javamail_api/javamail_api_sending_emails [メールの送信]で説明されている手順と似ていますが、ホストサーバーを変更する点が異なります。 前提条件として、送信者のメールアドレスはアクティブなGmailアカウントである必要があります。 例を試してみましょう。

Javaクラスを作成する

Javaファイル SendEmailUsingGMailSMTP を作成します。その内容は次のとおりです。

package com.finddevguides;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendEmailUsingGMailSMTP {
   public static void main(String[] args) {
     //Recipient's email ID needs to be mentioned.
      String to = "[email protected]";//change accordingly

     //Sender's email ID needs to be mentioned
      String from = "[email protected]";//change accordingly
      final String username = "abc";//change accordingly
      final String password = "*****";//change accordingly

     //Assuming you are sending email through relay.jangosmtp.net
      String host = "smtp.gmail.com";

      Properties props = new Properties();
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.starttls.enable", "true");
      props.put("mail.smtp.host", host);
      props.put("mail.smtp.port", "587");

     //Get the Session object.
      Session session = Session.getInstance(props,
      new javax.mail.Authenticator() {
         protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
         }
      });

      try {
        //Create a default MimeMessage object.
         Message message = new MimeMessage(session);

        //Set From: header field of the header.
         message.setFrom(new InternetAddress(from));

        //Set To: header field of the header.
         message.setRecipients(Message.RecipientType.TO,
         InternetAddress.parse(to));

        //Set Subject: header field
         message.setSubject("Testing Subject");

        //Now set the actual message
         message.setText("Hello, this is sample for to check send "
            + "email using JavaMailAPI ");

        //Send message
         Transport.send(message);

         System.out.println("Sent message successfully....");

      } catch (MessagingException e) {
            throw new RuntimeException(e);
      }
   }
}

ここでは、ホストは_smtp.gmail.com_として設定され、ポートは_587_として設定されます。 ここで、TLS接続を有効にしました。

コンパイルして実行する

クラスの準備ができたので、上記のクラスをコンパイルしましょう。 クラスSendEmailUsingGMailSMTP.javaをディレクトリに保存しました: /home/manisha/JavaMailAPIExercise 。 クラスパスに_javax.mail.jar_および_activation.jar_のjarが必要です。 以下のコマンドを実行して、コマンドプロンプトからクラス(両方のjarが/home/manisha/ディレクトリに配置されます)をコンパイルします。

javac -cp/home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendEmailUsingGMailSMTP.java

クラスがコンパイルされたので、次のコマンドを実行して実行します。

java -cp/home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendEmailUsingGMailSMTP

出力を検証する

コマンドコンソールに次のメッセージが表示されます。

Sent message successfully....

JavaMail API-フォルダー管理

これまで、前の章で主にINBOXフォルダーを使用してきました。 これは、ほとんどのメールが存在するデフォルトのフォルダーです。 一部のシステムはINBOXとして呼び出し、他のシステムは別の名前で呼び出します。 ただし、INBOXという名前を使用して、JavaMail APIからいつでもアクセスできます。

JavaMail APIは、抽象Folderクラスのインスタンスとしてフォルダーを表します。

public abstract class Folder extends Object

このクラスは、サーバーからの名前付きフォルダーの要求、フォルダーからのメッセージの削除、フォルダー内の特定のメッセージの検索、フォルダー内のメッセージのリストなどのメソッドを宣言します。

フォルダーを開く

_Folder_クラスの唯一のコンストラクターは_protected_であるため、フォルダーを直接作成することはできません。 _Folder_は次から取得できます。

  • セッション
  • 商店
  • または別のフォルダ

上記のすべてのクラスには、同様のシグネチャを持つ同様のgetFolder()メソッドがあります。

public abstract Folder getFolder(String name) throws MessagingException

_Folder_オブジェクトの取得に役立つメソッドの一部は次のとおりです。

Method Description
boolean exists() Checks if the folder really exists. Use this method before getting the Folder object.
abstract void open(int mode) When you get a Folder, its closed. Use this method to open it. mode can be Folder.READ_ONLY or Folder.READ_WRITE.
abstract boolean isOpen() This method returns true if the folder is open, false if it’s closed
abstract void close(boolean expunge) Closes the folder. If the expunge argument is true, any deleted messages in the folder are deleted from the actual file on the server. Otherwise, they’re simply marked as deleted, but the messages can still be undeleted.

基本的なフォルダー情報

以下は、フォルダーに関する基本情報を返すFolderクラスのメソッドの一部です。

Method Description
abstract String getName() Returns the name of the folder, such as "finddevguides Mail"
abstract String getFullName() Returns the complete hierarchical name from the root such as “books/Manisha/finddevguides Mail”.
URLName getURLName() Return a URLName representing this folder.
abstract Folder getParent() Returns the name of the folder that contains this folder i.e the parent folder. E.g "Manisha" from the previous "finddevguides Mail" example.
abstract int getType() Returns an int indicating whether the folder can contain messages and/or other folders.
int getMode() It returns one of the two named constants Folder.READ_ONLY or Folder.READ_WRITE or -1 when the mode is unknown.
Store getStore() Returns the Store object from which this folder was retrieved.
abstract char getSeparator() Return the delimiter character that separates this Folder’s pathname from the names of immediate subfolders.

フォルダーの管理

以下は、フォルダの管理に役立ついくつかの方法です。

Method Description
abstract boolean create(int type) This creates a new folder in this folder’s Store. Where type would be:Folder.HOLDS_MESSAGES or Folder.HOLDS_FOLDERS. Returns true if folder is successfully created else returns false.
abstract boolean delete(boolean recurse) This deletes the folder only if the folder is closed. Otherwise, it throws an IllegalStateException. If recurse is true, then subfolders are deleted.
abstract boolean renameTo(Folder f) This changes the name of this folder. A folder must be closed to be renamed. Otherwise, an IllegalStateException is thrown.

フォルダー内のメッセージの管理

以下は、フォルダ内のメッセージの管理に役立つメソッドの一部です。

Method Description
abstract void appendMessages(Message[] messages) As the name implies, the messages in the array are placed at the end of this folder.
void copyMessages(Message[] messages, Folder destination) This copies messages from this folder into a specified folder given as an argument.
abstract Message[] expunge() To delete a message from a folder, set its Flags.Flag.DELETED flag to true. To physically remove deleted messages from a folder, you have to call this method.

フォルダーの内容のリスト

フォルダーに含まれるフォルダーをリストするには、4つの方法があります。

Method Description
Folder[] list() This returns an array listing the folders that this folder contains.
Folder[] listSubscribed() This returns an array listing all the subscribed folders that this folder contains.
abstract Folder[] list(String pattern) This is similar to the list() method except that it allows you to specify a pattern. The pattern is a string giving the name of the folders that match.
Folder[] listSubscribed(String pattern) This is similar to the listSubscribed() method except that it allows you to specify a pattern. The pattern is a string giving the name of the folders that match.

メールの確認

Method Description
abstract int getMessageCount() This method can be invoked on an open or closed folder. However, in the case of a closed folder, this method may (or may not) return -1 to indicate that the exact number of messages isn’t easily available.
abstract boolean hasNewMessages() This returns true if new messages have been added to the folder since it was last opened.
int getNewMessageCount() It returns the new message count by checking messages in the folder whose RECENT flag is set.
int getUnreadMessageCount() This can be invoked on either an open or a closed folder. However, in the case of a closed folder, it may return -1 to indicate that the real answer would be too expensive to obtain.

フォルダーからメッセージを取得する

Folderクラスには、開いているフォルダーからメッセージを取得するための4つのメソッドがあります。

Method Description
abstract Message getMessage(int messageNumber) This returns the nth message in the folder. The first message in the folder is number 1.
Message[] getMessages() This returns an array of Message objects representing all the messages in this folder.
Message[] getMessages(int start, int end) This returns an array of Message objects from the folder, beginning with start and finishing with end, inclusive.
Message[] getMessages(int[] messageNumbers) This returns an array containing only those messages specifically identified by number in the messageNumbers array.
void fetch(Message[] messages, FetchProfile fp) Prefetch the items specified in the FetchProfile for the given Messages. The FetchProfile argument specifies which headers in the messages to prefetch.

フォルダーを検索する

サーバーが検索をサポートしている場合(多くのIMAPサーバーがサポートし、ほとんどのPOPサーバーがサポートしない場合)、特定の条件を満たすメッセージをフォルダーで簡単に検索できます。 条件はSearchTermオブジェクトにエンコードされます。 次の2つの検索方法があります。

Method Description
Message[] search(SearchTerm term) Search this Folder for messages matching the specified search criterion. Returns an array containing the matching messages. Returns an empty array if no matches were found.
Message[] search(SearchTerm term, Message[] messages) Search the given array of messages for those that match the specified search criterion. Returns an array containing the matching messages. Returns an empty array if no matches were found. The the specified Message objects must belong to this folder.

フラグ

フラグの変更は、フォルダ内のメッセージセット全体のフラグを変更する必要がある場合に便利です。 以下は、Folderクラスで提供されるメソッドです。

Method Description
void setFlags(Message[] messages, Flags flag, boolean value) Sets the specified flags on the messages specified in the array.
void setFlags(int start, int end, Flags flag, boolean value) Sets the specified flags on the messages numbered from start through end, both start and end inclusive.
void setFlags(int[] messageNumbers, Flags flag, boolean value) Sets the specified flags on the messages whose message numbers are in the array.
abstract Flags getPermanentFlags() Returns the flags that this folder supports for all messages.

JavaMail API-クォータ管理

JavaMailのクォータは、電子メールストア内のメッセージの制限または固定数または量です。 各メールサービスリクエストは、JavaMail APIコールクォータにカウントされます。 メールサービスは、次のクォータ基準を適用できます。

  • 添付ファイルを含む送信メールメッセージの最大サイズ。
  • 添付ファイルを含む受信メールメッセージの最大サイズ。
  • 管理者が受信者である場合のメッセージの最大サイズ

クォータ管理のために、JavaMailには次のクラスがあります。

Class Description
public class Quota This class represents a set of quotas for a given quota root. Each quota root has a set of resources, represented by the Quota.Resource class. Each resource has a name (for example, "STORAGE"), a current usage, and a usage limit. This has only one method setResourceLimit(String name, long limit).
public static class Quota.Resource Represents an individual resource in a quota root.
public interface QuotaAwareStore An interface implemented by Stores that support quotas. The getQuota and setQuota methods support the quota model defined by the IMAP QUOTA extension. GmailSSLStore, GmailStore, IMAPSSLStore, IMAPStore are the known implementing classes of this interface.

次のセクションで、メールストレージ名、制限、およびその使用法を確認する例を見てみましょう。

Javaクラスを作成する

Javaクラスファイル QuotaExample を作成します。その内容は次のとおりです。

package com.finddevguides;

import java.util.Properties;

import javax.mail.Quota;
import javax.mail.Session;
import javax.mail.Store;

import com.sun.mail.imap.IMAPStore;

public class QuotaExample
{
   public static void main(String[] args)
   {
      try
      {
         Properties properties = new Properties();
         properties.put("mail.store.protocol", "imaps");
         properties.put("mail.imaps.port", "993");
         properties.put("mail.imaps.starttls.enable", "true");
         Session emailSession = Session.getDefaultInstance(properties);
        //emailSession.setDebug(true);

        //create the IMAP3 store object and connect with the pop server
         Store store = emailSession.getStore("imaps");

        //change the user and password accordingly
         store.connect("imap.gmail.com", "[email protected]", "*****");
         IMAPStore imapStore = (IMAPStore) store;
         System.out.println("imapStore ---" + imapStore);

        //get quota
         Quota[] quotas = imapStore.getQuota("INBOX");
        //Iterate through the Quotas
         for (Quota quota : quotas) {
            System.out.println(String.format("quotaRoot:'%s'",
               quota.quotaRoot));
           //Iterate through the Quota Resource
            for (Quota.Resource resource : quota.resources) {
               System.out.println(String.format(
                  "name:'%s', limit:'%s', usage:'%s'", resource.name,
                  resource.limit, resource.usage));
            }
         }
      } catch (Exception e)
      {
         e.printStackTrace();
      }
   }
}

IMAPStoreはQuotaAwareStoreを実装しているため、IMAP(imap.gmail.com)サーバーを介したgmailサービスへの接続は次のとおりです。 Storeオブジェクトを取得したら、Quota配列を取得して繰り返し処理し、関連情報を出力します。

コンパイルして実行する

クラスの準備ができたので、上記のクラスをコンパイルしましょう。 クラスQuotaExample.javaをディレクトリ /home/manisha/JavaMailAPIExercise に保存しました。 クラスパスに_javax.mail.jar_および_activation.jar_のjarが必要です。 以下のコマンドを実行して、コマンドプロンプトからクラス(両方のjarが/home/manisha/ディレクトリに配置されます)をコンパイルします。

javac -cp/home/manisha/activation.jar:/home/manisha/javax.mail.jar: QuotaExample.java

クラスがコンパイルされたので、次のコマンドを実行して実行します。

java -cp/home/manisha/activation.jar:/home/manisha/javax.mail.jar: QuotaExample

出力を検証する

コマンドコンソールに同様のメッセージが表示されます。

imapStore ---imaps://abc%[email protected]
quotaRoot:''
name:'STORAGE', limit:'15728640', usage:'513'

JavaMail API-バウンスされたメッセージ

メッセージはいくつかの理由で返送されます。 この問題については、http://www.rfc-editor.org/info/rfc1211 [rfc1211]で詳しく説明されています。 サーバーのみが特定のメールボックスまたはユーザー名の存在を判断できます。 サーバーは、エラーを検出すると、失敗の理由を示すメッセージを元のメッセージの送信者に返します。

配信ステータス通知をカバーする多くのインターネット標準がありますが、多くのサーバーはこれらの新しい標準をサポートせず、代わりにそのような失敗メッセージを返すためのアドホック技術を使用します。 したがって、_bounced_メッセージを問題の原因となった元のメッセージと関連付けることは非常に困難になります。

JavaMailには、配信ステータス通知の解析のサポートが含まれています。 この問題に対処するための多くのテクニックとヒューリスティックがあります。 可変エンベロープリターンパスである手法の1つ。 以下の例に示すように、エンベロープでリターンパスを設定できます。 これは、バウンスメールの送信先アドレスです。 これを、From:ヘッダーとは異なる汎用アドレスに設定すると、リモートバウンスを処理できます。 これは、JavaMailで_mail.smtp.from_プロパティを設定することにより行われます。

Javaクラスを作成する

Javaクラスファイル SendEmail を作成します。その内容は次のとおりです。

import java.util.Properties;

import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendEmail {
   public static void main(String[] args) throws Exception {
      String smtpServer = "smtp.gmail.com";
      int port = 587;
      final String userid = "youraddress";//change accordingly
      final String password = "*****";//change accordingly
      String contentType = "text/html";
      String subject = "test: bounce an email to a different address " +
                "from the sender";
      String from = "[email protected]";
      String to = "[email protected]";//some invalid address
      String bounceAddr = "[email protected]";//change accordingly
      String body = "Test: get message to bounce to a separate email address";

      Properties props = new Properties();

      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.starttls.enable", "true");
      props.put("mail.smtp.host", smtpServer);
      props.put("mail.smtp.port", "587");
      props.put("mail.transport.protocol", "smtp");
      props.put("mail.smtp.from", bounceAddr);

      Session mailSession = Session.getInstance(props,
         new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
               return new PasswordAuthentication(userid, password);
            }
         });

      MimeMessage message = new MimeMessage(mailSession);
      message.addFrom(InternetAddress.parse(from));
      message.setRecipients(Message.RecipientType.TO, to);
      message.setSubject(subject);
      message.setContent(body, contentType);

      Transport transport = mailSession.getTransport();
      try {
         System.out.println("Sending ....");
         transport.connect(smtpServer, port, userid, password);
         transport.sendMessage(message,
            message.getRecipients(Message.RecipientType.TO));
         System.out.println("Sending done ...");
      } catch (Exception e) {
         System.err.println("Error Sending: ");
         e.printStackTrace();

      }
      transport.close();
   }//end function main()
}

ここで、プロパティ_mail.smtp.from_が_from_アドレスとは異なるように設定されていることがわかります。

コンパイルして実行する

クラスの準備ができたので、上記のクラスをコンパイルしましょう。 クラスSendEmail.javaをディレクトリ /home/manisha/JavaMailAPIExercise に保存しました。 クラスパスに_javax.mail.jar_および_activation.jar_のjarが必要です。 以下のコマンドを実行して、コマンドプロンプトからクラス(両方のjarが/home/manisha/ディレクトリに配置されます)をコンパイルします。

javac -cp/home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendEmail.java

クラスがコンパイルされたので、次のコマンドを実行して実行します。

java -cp/home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendEmail

出力を検証する

コマンドコンソールに次のメッセージが表示されます。

Sending ....
Sending done ...

JavaMail API-SMTPサーバー

SMTPは Simple Mail Transfer Protocol の頭字語です。 これは、インターネットプロトコル(IP)ネットワークを介した電子メール(電子メール)伝送のインターネット標準です。 SMTPはTCPポート25を使用します。 SMTPSはそれ自体ではプロトコルではありませんが、SSLで保護されたSMTP接続は簡易SMTPSで知られています。

JavaMail APIには、SMTPサーバーにアクセスするためのSMTPプロトコルプロバイダーとして機能するパッケージ com.sun.mail.smtp があります。 次の表に、このパッケージに含まれるクラスを示します。

Class Description
SMTPMessage This class is a specialization of the MimeMessage class that allows you to specify various SMTP options and parameters that will be used when this message is sent over SMTP.
SMTPSSLTransport This class implements the Transport abstract class using SMTP over SSL for message submission and transport.
SMTPTransport This class implements the Transport abstract class using SMTP for message submission and transport.

次の表に、スローされる例外を示します。

Exception Description
SMTPAddressFailedException This exception is thrown when the message cannot be sent.
SMTPAddressSucceededException This exception is chained off a SendFailedException when the mail.smtp.reportsuccess property is true.
SMTPSenderFailedException This exception is thrown when the message cannot be sent.
SMTPSendFailedException This exception is thrown when the message cannot be sent.The exception includes the sender’s address, which the mail server rejected.
*_com.sun.mail.smtp_* プロバイダーは、オプションでSMTP認証を使用します。 SMTP認証を使用するには、SMTPサーバーに接続するときに_mail.smtp.auth_プロパティを設定するか、SMTPトランスポートにユーザー名とパスワードを提供する必要があります。 これは、次のアプローチのいずれかを使用して実行できます。
  • メールセッションの作成時に認証システムオブジェクトを提供し、認証システムコールバック中にユーザー名とパスワード情報を提供します。 _mail.smtp.user_プロパティを設定して、コールバックのデフォルトのユーザー名を指定できますが、パスワードを明示的に指定する必要があります。 このアプローチにより、静的なトランスポート送信メソッドを使用してメッセージを送信できます。 例えば:
Transport.send(message);

ユーザー名とパスワードの引数を使用して、トランスポート接続メソッドを明示的に呼び出します。 例えば:

Transport tr = session.getTransport("smtp");
tr.connect(smtphost, username, password);
msg.saveChanges();
tr.sendMessage(msg, msg.getAllRecipients());
tr.close();

SMTPプロトコルプロバイダーは、JavaMail Sessionオブジェクトで設定できる以下のプロパティをサポートします。 プロパティは常に文字列として設定されます。 例えば:

 props.put("mail.smtp.port", "587");

ここで、 Type 列は、文字列の解釈方法を説明しています。

Name Type Description
mail.smtp.user String Default user name for SMTP.
mail.smtp.host String The SMTP server to connect to.
mail.smtp.port int The SMTP server port to connect to, if the connect() method doesn’t explicitly specify one. Defaults to 25.
mail.smtp.connectiontimeout int Socket connection timeout value in milliseconds. Default is infinite timeout.
mail.smtp.timeout int Socket I/O timeout value in milliseconds. Default is infinite timeout.
mail.smtp.from String Email address to use for SMTP MAIL command. This sets the envelope return address. Defaults to msg.getFrom() or InternetAddress.getLocalAddress().
mail.smtp.localhost String Local host name used in the SMTP HELO or EHLO command. Defaults to InetAddress.getLocalHost().getHostName(). Should not normally need to be set if your JDK and your name service are configured properly.
mail.smtp.localaddress String Local address (host name) to bind to when creating the SMTP socket. Defaults to the address picked by the Socket class. Should not normally need to be set.
mail.smtp.localport int Local port number to bind to when creating the SMTP socket. Defaults to the port number picked by the Socket class.
mail.smtp.ehlo boolean If false, do not attempt to sign on with the EHLO command. Defaults to true.
mail.smtp.auth boolean If true, attempt to authenticate the user using the AUTH command. Defaults to false.
mail.smtp.auth.mechanisms String If set, lists the authentication mechanisms to consider. Only mechanisms supported by the server and supported by the current implementation will be used. The default is "LOGIN PLAIN DIGEST-MD5 NTLM", which includes all the authentication mechanisms supported by the current implementation.
mail.smtp.auth.login.disable boolean If true, prevents use of the AUTH LOGIN command. Default is false.
mail.smtp.auth.plain.disable boolean If true, prevents use of the AUTH PLAIN command. Default is false.
mail.smtp.auth.digest-md5.disable boolean If true, prevents use of the AUTH DIGEST-MD5 command. Default is false.
mail.smtp.auth.ntlm.disable boolean If true, prevents use of the AUTH NTLM command. Default is false.
mail.smtp.auth.ntlm.domain String The NTLM authentication domain.
mail.smtp.auth.ntlm.flags int NTLM protocol-specific flags.
mail.smtp.submitter String The submitter to use in the AUTH tag in the MAIL FROM command. Typically used by a mail relay to pass along information about the original submitter of the message.
mail.smtp.dsn.notify String The NOTIFY option to the RCPT command. Either NEVER, or some combination of SUCCESS, FAILURE, and DELAY (separated by commas).
mail.smtp.dsn.ret String The RET option to the MAIL command. Either FULL or HDRS.
mail.smtp.sendpartial boolean If set to true, and a message has some valid and some invalid addresses, send the message anyway, reporting the partial failure with a SendFailedException. If set to false (the default), the message is not sent to any of the recipients if there is an invalid recipient address.
mail.smtp.sasl.enable boolean If set to true, attempt to use the javax.security.sasl package to choose an authentication mechanism for login. Defaults to false.
mail.smtp.sasl.mechanisms String A space or comma separated list of SASL mechanism names to try to use.
mail.smtp.sasl.authorizationid String The authorization ID to use in the SASL authentication. If not set, the authentication ID (user name) is used.
mail.smtp.sasl.realm String The realm to use with DIGEST-MD5 authentication.
mail.smtp.quitwait boolean If set to false, the QUIT command is sent and the connection is immediately closed. If set to true (the default), causes the transport to wait for the response to the QUIT command.
mail.smtp.reportsuccess boolean If set to true, causes the transport to include an SMTPAddressSucceededException for each address that is successful.
mail.smtp.socketFactory Socket Factory If set to a class that implements the javax.net.SocketFactory interface, this class will be used to create SMTP sockets.
mail.smtp.socketFactory.class String If set, specifies the name of a class that implements the javax.net.SocketFactory interface. This class will be used to create SMTP sockets.
mail.smtp.socketFactory.fallback boolean If set to true, failure to create a socket using the specified socket factory class will cause the socket to be created using the java.net.Socket class. Defaults to true.
mail.smtp.socketFactory.port int Specifies the port to connect to when using the specified socket factory. If not set, the default port will be used.
mail.smtp.ssl.enable boolean If set to true, use SSL to connect and use the SSL port by default. Defaults to false for the "smtp" protocol and true for the "smtps" protocol.
mail.smtp.ssl.checkserveridentity boolean If set to true, checks the server identity as specified by RFC 2595. Defaults to false.
mail.smtp.ssl.trust String If set, and a socket factory hasn’t been specified, enables use of a MailSSLSocketFactory. If set to "*", all hosts are trusted. If set to a whitespace separated list of hosts, those hosts are trusted. Otherwise, trust depends on the certificate the server presents.
mail.smtp.ssl.socketFactory SSL Socket Factory If set to a class that extends the javax.net.ssl.SSLSocketFactory class, this class will be used to create SMTP SSL sockets.
mail.smtp.ssl.socketFactory.class String If set, specifies the name of a class that extends the javax.net.ssl.SSLSocketFactory class. This class will be used to create SMTP SSL sockets.
mail.smtp.ssl.socketFactory.port int Specifies the port to connect to when using the specified socket factory. If not set, the default port will be used.
mail.smtp.ssl.protocols string Specifies the SSL protocols that will be enabled for SSL connections. The property value is a whitespace separated list of tokens acceptable to the javax.net.ssl.SSLSocket.setEnabledProtocols method.
mail.smtp.starttls.enable boolean If true, enables the use of the STARTTLS command (if supported by the server) to switch the connection to a TLS-protected connection before issuing any login commands. Defaults to false.
mail.smtp.starttls.required boolean If true, requires the use of the STARTTLS command. If the server doesn’t support the STARTTLS command, or the command fails, the connect method will fail. Defaults to false.
mail.smtp.socks.host string Specifies the host name of a SOCKS5 proxy server that will be used for connections to the mail server.
mail.smtp.socks.port string Specifies the port number for the SOCKS5 proxy server. This should only need to be used if the proxy server is not using the standard port number of 1080.
mail.smtp.mailextension String Extension string to append to the MAIL command.
mail.smtp.userset boolean If set to true, use the RSET command instead of the NOOP command in the isConnected method. In some cases sendmail will respond slowly after many NOOP commands; use of RSET avoids this sendmail issue. Defaults to false.

一般に、アプリケーションはこのパッケージのクラスを直接使用する必要はありません。 代わりに、javax.mailパッケージ(およびサブパッケージ)で定義されたAPIを使用する必要があります。 たとえば、アプリケーションでSMTPTransportのインスタンスを直接構築しないでください。 代わりに、SessionメソッドgetTransportを使用して適切なTransportオブジェクトを取得する必要があります。

SMPTサーバーの使用例は、章のリンク:/javamail_api/javamail_api_sending_emails [Sending Emails]に示されています。

JavaMail API-IMAPサーバー

IMAPは Internet Message Access Protocol の頭字語です。 これは、電子メールクライアントがリモートメールサーバー上の電子メールにアクセスできるようにするアプリケーション層インターネットプロトコルです。 IMAPサーバーは通常、既知のポート143でリッスンします。 IMAP over SSL(IMAPS)はポート番号993に割り当てられます。

IMAPは、オンラインとオフラインの両方の操作モードをサポートしています。 IMAPを使用する電子メールクライアントは、通常、ユーザーがメッセージを明示的に削除するまでサーバーにメッセージを残します。

パッケージ com.sun.mail.imap は、IMAPメッセージストアへのアクセスを提供するJavaMail APIのIMAPプロトコルプロバイダーです。 次の表に、このプロバイダーのインターフェイスとクラスを示します。

Class/Interface Description
IMAPFolder.ProtocolCommand This a simple interface for user-defined IMAP protocol commands.
ACL This is a class. An access control list entry for a particular authentication identifier (user or group).
IMAPFolder This class implements an IMAP folder.
IMAPFolder.FetchProfileItem This a class for fetching headers.
IMAPMessage This class implements an ReadableMime object.
IMAPMessage.FetchProfileCondition This class implements the test to be done on each message in the folder.
IMAPSSLStore This class provides access to an IMAP message store over SSL.
IMAPStore This class provides access to an IMAP message store.
Rights This class represents the set of rights for an authentication identifier (for instance, a user or a group).
Rights.Right This inner class represents an individual right.
SortTerm A particular sort criteria, as defined by RFC 5256.

このプロバイダーの上に注意すべきいくつかのポイント:

  • このプロバイダーは、IMAP4プロトコルとIMAP4rev1プロトコルの両方をサポートしています。
  • 接続されたIMAPStoreは、IMAPサーバーとの通信に使用するIMAPプロトコルオブジェクトのプールを保持します。 フォルダーが開かれ、新しいIMAPプロトコルオブジェクトが必要になると、IMAPStoreはそれらを接続プールから提供するか、使用できない場合は作成します。 フォルダーが閉じられると、そのIMAPプロトコルオブジェクトがプールの場合、接続プールに返されます。 *接続されたIMAPStoreオブジェクトは、ストアにIMAPサーバーへの専用接続を提供する個別のIMAPプロトコルオブジェクトを保持する場合と保持しない場合があります。

IMAPプロトコルプロバイダーは、JavaMail Sessionオブジェクトで設定できる以下のプロパティをサポートします。 プロパティは常に文字列として設定されます。* Type *列は、文字列の解釈方法を説明しています。

Name Type Description
mail.imap.user String Default user name for IMAP.
mail.imap.host String The IMAP server to connect to.
mail.imap.port int The IMAP server port to connect to, if the connect() method doesn’t explicitly specify one. Defaults to 143.
mail.imap.partialfetch boolean Controls whether the IMAP partial-fetch capability should be used. Defaults to true.
mail.imap.fetchsize int Partial fetch size in bytes. Defaults to 16K.
mail.imap.ignorebodystructuresize boolean The IMAP BODYSTRUCTURE response includes the exact size of each body part. Normally, this size is used to determine how much data to fetch for each body part. Defaults to false.
mail.imap.connectiontimeout int Socket connection timeout value in milliseconds. Default is infinite timeout.
mail.imap.timeout int Socket I/O timeout value in milliseconds. Default is infinite timeout.
mail.imap.statuscachetimeout int Timeout value in milliseconds for cache of STATUS command response. Default is 1000 (1 second). Zero disables cache.
mail.imap.appendbuffersize int Maximum size of a message to buffer in memory when appending to an IMAP folder.
mail.imap.connectionpoolsize int Maximum number of available connections in the connection pool. Default is 1.
mail.imap.connectionpooltimeout int Timeout value in milliseconds for connection pool connections. Default is 45000 (45 seconds).
mail.imap.separatestoreconnection boolean Flag to indicate whether to use a dedicated store connection for store commands. Default is false.
mail.imap.auth.login.disable boolean If true, prevents use of the non-standard AUTHENTICATE LOGIN command, instead using the plain LOGIN command. Default is false.
mail.imap.auth.plain.disable boolean If true, prevents use of the AUTHENTICATE PLAIN command. Default is false.
mail.imap.auth.ntlm.disable boolean If true, prevents use of the AUTHENTICATE NTLM command. Default is false.
mail.imap.proxyauth.user String If the server supports the PROXYAUTH extension, this property specifies the name of the user to act as. Authenticate to the server using the administrator’s credentials. After authentication, the IMAP provider will issue the PROXYAUTH command with the user name specified in this property.
mail.imap.localaddress String Local address (host name) to bind to when creating the IMAP socket. Defaults to the address picked by the Socket class.
mail.imap.localport int Local port number to bind to when creating the IMAP socket. Defaults to the port number picked by the Socket class.
mail.imap.sasl.enable boolean If set to true, attempt to use the javax.security.sasl package to choose an authentication mechanism for login. Defaults to false.
mail.imap.sasl.mechanisms String A space or comma separated list of SASL mechanism names to try to use.
mail.imap.sasl.authorizationid String The authorization ID to use in the SASL authentication. If not set, the authentication ID (user name) is used.
mail.imap.sasl.realm String The realm to use with SASL authentication mechanisms that require a realm, such as DIGEST-MD5.
mail.imap.auth.ntlm.domain String The NTLM authentication domain.
mail.imap.auth.ntlm.flags int NTLM protocol-specific flags.
mail.imap.socketFactory Socket Factory If set to a class that implements the javax.net.SocketFactory interface, this class will be used to create IMAP sockets.
mail.imap.socketFactory.class String If set, specifies the name of a class that implements the javax.net.SocketFactory interface. This class will be used to create IMAP sockets.
mail.imap.socketFactory.fallback boolean If set to true, failure to create a socket using the specified socket factory class will cause the socket to be created using the java.net.Socket class. Defaults to true.
mail.imap.socketFactory.port int Specifies the port to connect to when using the specified socket factory. Default port is used when not set.
mail.imap.ssl.enable boolean If set to true, use SSL to connect and use the SSL port by default. Defaults to false for the "imap" protocol and true for the "imaps" protocol.
mail.imap.ssl.checkserveridentity boolean If set to true, check the server identity as specified by RFC 2595. Defaults to false.
mail.imap.ssl.trust String If set, and a socket factory hasn’t been specified, enables use of a MailSSLSocketFactory. If set to "*", all hosts are trusted. If set to a whitespace separated list of hosts, those hosts are trusted. Otherwise, trust depends on the certificate the server presents.
mail.imap.ssl.socketFactory SSL Socket Factory If set to a class that extends the javax.net.ssl.SSLSocketFactory class, this class will be used to create IMAP SSL sockets.
mail.imap.ssl.socketFactory.class String If set, specifies the name of a class that extends the javax.net.ssl.SSLSocketFactory class. This class will be used to create IMAP SSL sockets.
mail.imap.ssl.socketFactory.port int Specifies the port to connect to when using the specified socket factory. If not set, the default port will be used.
mail.imap.ssl.protocols string Specifies the SSL protocols that will be enabled for SSL connections. The property value is a whitespace separated list of tokens acceptable to the javax.net.ssl.SSLSocket.setEnabledProtocols method.
mail.imap.starttls.enable boolean If true, enables the use of the STARTTLS command (if supported by the server) to switch the connection to a TLS-protected connection before issuing any login commands. Default is false.
mail.imap.starttls.required boolean If true, requires the use of the STARTTLS command. If the server doesn’t support the STARTTLS command, or the command fails, the connect method will fail. Defaults to false.
mail.imap.socks.host string Specifies the host name of a SOCKS5 proxy server that will be used for connections to the mail server.
mail.imap.socks.port string Specifies the port number for the SOCKS5 proxy server. This should only need to be used if the proxy server is not using the standard port number of 1080.
mail.imap.minidletime int This property sets the delay in milliseconds. If not set, the default is 10 milliseconds.
mail.imap.enableimapevents boolean Enable special IMAP-specific events to be delivered to the Store’s ConnectionListener. If true, unsolicited responses received during the Store’s idle method will be sent as ConnectionEvents with a type of IMAPStore.RESPONSE. The event’s message will be the raw IMAP response string. By default, these events are not sent.
mail.imap.folder.class String Class name of a subclass of com.sun.mail.imap.IMAPFolder. The subclass can be used to provide support for additional IMAP commands. The subclass must have public constructors of the form public MyIMAPFolder(String fullName, char separator, IMAPStore store, Boolean isNamespace) and public MyIMAPFolder(ListInfo li, IMAPStore store)

一般に、アプリケーションはこのパッケージのクラスを直接使用する必要はありません。 代わりに、javax.mailパッケージ(およびサブパッケージ)で定義されたAPIを使用する必要があります。 アプリケーションは、IMAPStoreまたはIMAPFolderのインスタンスを直接構築しないでください。 代わりに、SessionメソッドgetStoreを使用して適切なStoreオブジェクトを取得し、そこからFolderオブジェクトを取得する必要があります。

IMAPサーバーの使用例は、リンク:/javamail_api/javamail_api_quota_management [Quota Management]で説明されています。

JavaMail API-POP3サーバー

Post Office Protocol(POP)は、TCP/IP接続を介してリモートサーバーから電子メールを取得するためにローカル電子メールクライアントが使用するアプリケーション層のインターネット標準プロトコルです。 POPは、リモートメールボックスにアクセスするための簡単なダウンロードと削除の要件をサポートしています。 POP3サーバーは、既知のポート110でリッスンします。

パッケージ com.sun.mail.pop3 は、POP3メッセージストアへのアクセスを提供するJavaMail APIのPOP3プロトコルプロバイダーです。 次の表に、このパッケージのクラスを示します。

Name Description
POP3Folder A POP3 Folder (can only be "INBOX").
POP3Message A POP3 Message.
POP3SSLStore A POP3 Message Store using SSL.
POP3Store A POP3 Message Store.

このプロバイダーの上に注意すべきいくつかのポイント:

  • POP3プロバイダーは、 INBOX という名前の単一のフォルダーのみをサポートします。 POP3プロトコルの制限により、イベント通知、フォルダー管理、フラグ管理などのJavaMail API機能の多く 許可されていません。
  • POP3プロバイダーには、プロトコル名_pop3_または_pop3://user:password @ host:port/INBOX "_の形式のURLを使用して、JavaMail APIからアクセスします。
  • POP3は永続的なフラグをサポートしていません。 たとえば、_Flags.Flag.RECENT_フラグは、POP3メッセージには設定されません。 POP3メールボックスのどのメッセージが_new_であるかを判断するのはアプリケーション次第です。
  • POP3はFolder.expunge()メソッドをサポートしていません。 メッセージを削除および消去するには、メッセージにFlags.Flag.DELETEDフラグを設定し、Folder.close(true)メソッドを使用してフォルダーを閉じます。
  • POP3は_received date_を提供しないため、getReceivedDateメソッドはnullを返します。
  • POP3メッセージのヘッダーにアクセスすると、POP3プロバイダーはTOPコマンドを使用してすべてのヘッダーを取得し、その後、キャッシュします。
  • POP3メッセージのコンテンツにアクセスすると、POP3プロバイダーはRETRコマンドを使用してメッセージ全体を取得します。
  • _POP3Message.invalidate_メソッドを使用すると、フォルダーを閉じずにキャッシュされたデータを無効にできます。

POP3プロトコルプロバイダーは、JavaMail Sessionオブジェクトで設定できる以下のプロパティをサポートします。 プロパティは常に文字列として設定されます。 「タイプ」列は、ストリングの解釈方法を説明しています。

Name Type Description
mail.pop3.user String Default user name for POP3.
mail.pop3.host String The POP3 server to connect to.
mail.pop3.port int The POP3 server port to connect to, if the connect() method doesn’t explicitly specify one. Defaults to 110.
mail.pop3.connectiontimeout int Socket connection timeout value in milliseconds. Default is infinite timeout.
mail.pop3.timeout int Socket I/O timeout value in milliseconds. Default is infinite timeout.
mail.pop3.rsetbeforequit boolean Send a POP3 RSET command when closing the folder, before sending the QUIT command. Default is false.
mail.pop3.message.class String Class name of a subclass of com.sun.mail.pop3.POP3Message. The subclass can be used to handle (for example) non-standard Content-Type headers. The subclass must have a public constructor of the form MyPOP3Message(Folder f, int msgno) throws MessagingException.
mail.pop3.localaddress String Local address (host name) to bind to when creating the POP3 socket. Defaults to the address picked by the Socket class.
mail.pop3.localport int Local port number to bind to when creating the POP3 socket. Defaults to the port number picked by the Socket class.
mail.pop3.apop.enable boolean If set to true, use APOP instead of USER/PASS to login to the POP3 server, if the POP3 server supports APOP. APOP sends a digest of the password rather than the clear text password. Defaults to false.
mail.pop3.socketFactory Socket Factory If set to a class that implements the javax.net.SocketFactory interface, this class will be used to create POP3 sockets.
mail.pop3.socketFactory.class String If set, specifies the name of a class that implements the javax.net.SocketFactory interface. This class will be used to create POP3 sockets.
mail.pop3.socketFactory.fallback boolean If set to true, failure to create a socket using the specified socket factory class will cause the socket to be created using the java.net.Socket class. Defaults to true.
mail.pop3.socketFactory.port int Specifies the port to connect to when using the specified socket factory. If not set, the default port will be used.
mail.pop3.ssl.enable boolean If set to true, use SSL to connect and use the SSL port by default. Defaults to false for the "pop3" protocol and true for the "pop3s" protocol.
mail.pop3.ssl.checkserveridentity boolean If set to true, check the server identity as specified by RFC 2595. Defaults to false.
mail.pop3.ssl.trust String If set, and a socket factory hasn’t been specified, enables use of a MailSSLSocketFactory. If set to "*", all hosts are trusted. If set to a whitespace separated list of hosts, those hosts are trusted. Otherwise, trust depends on the certificate the server presents.
mail.pop3.ssl.socketFactory SSL Socket Factory If set to a class that extends the javax.net.ssl.SSLSocketFactory class, this class will be used to create POP3 SSL sockets.
mail.pop3.ssl.socketFactory.class String If set, specifies the name of a class that extends the javax.net.ssl.SSLSocketFactory class. This class will be used to create POP3 SSL sockets.
mail.pop3.ssl.socketFactory.port int Specifies the port to connect to when using the specified socket factory. If not set, the default port will be used.
mail.pop3.ssl.protocols string Specifies the SSL protocols that will be enabled for SSL connections. The property value is a whitespace separated list of tokens acceptable to the javax.net.ssl.SSLSocket.setEnabledProtocols method.
mail.pop3.starttls.enable boolean If true, enables the use of the STLS command (if supported by the server) to switch the connection to a TLS-protected connection before issuing any login commands. Defaults to false.
mail.pop3.starttls.required boolean If true, requires the use of the STLS command. If the server doesn’t support the STLS command, or the command fails, the connect method will fail. Defaults to false.
mail.pop3.socks.host string Specifies the host name of a SOCKS5 proxy server that will be used for connections to the mail server.
mail.pop3.socks.port string Specifies the port number for the SOCKS5 proxy server.
mail.pop3.disabletop boolean If set to true, the POP3 TOP command will not be used to fetch message headers. Defaults to false.
mail.pop3.forgettopheaders boolean If set to true, the headers that might have been retrieved using the POP3 TOP command will be forgotten and replaced by headers retrieved as part of the POP3 RETR command. Defaults to false.
mail.pop3.filecache.enable boolean If set to true, the POP3 provider will cache message data in a temporary file rather than in memory. Messages are only added to the cache when accessing the message content. Message headers are always cached in memory (on demand). The file cache is removed when the folder is closed or the JVM terminates. Defaults to false.
mail.pop3.filecache.dir String If the file cache is enabled, this property can be used to override the default directory used by the JDK for temporary files.
mail.pop3.cachewriteto boolean Controls the behavior of the writeTo method on a POP3 message object. If set to true, and the message content hasn’t yet been cached, and ignoreList is null, the message is cached before being written. Otherwise, the message is streamed directly to the output stream without being cached. Defaults to false.
mail.pop3.keepmessagecontent boolean If this property is set to true, a hard reference to the cached content will be kept, preventing the memory from being reused until the folder is closed or the cached content is explicitly invalidated (using the invalidate method). Defaults to false.

一般に、アプリケーションはこのパッケージのクラスを直接使用しないでください。 代わりに、_javax.mail_パッケージ(およびサブパッケージ)で定義されたAPIを使用する必要があります。 アプリケーションは、_POP3Store_または_POP3Folder_のインスタンスを直接構築しないでください。 代わりに、SessionメソッドgetStoreを使用して適切なStoreオブジェクトを取得し、そこからFolderオブジェクトを取得する必要があります。

POP3サーバーの使用例は、リンク:/javamail_api/javamail_api_checking_emails [Checking Emails]に示されています。