Javamail-api-forwarding-emails

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

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転送メール]