Javamail-api-deleting-emails

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

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