JavaMail 電子郵件答復/回復


在本章中,我們將看到如何使用JavaMail API來回復電子郵件。接著在下面的程式中的列出基本步驟:

  • 獲取Session物件與POP和SMTP 伺服器的細節屬性。我們需要 POP 細節來檢索資訊和SMPT詳細資訊傳送郵件。

  • 建立POP3儲存物件,並連線到儲存。

  • 建立檔案夾物件,並在您的郵箱中開啟相應的檔案夾。

  • 檢索訊息。

  • 遍歷的訊息,如果你想回復鍵入“Y”或“y”。

  • 得到訊息的所有資訊(收件人,發件人,主題,內容)(To,From,Subject, Content) 。

  • 建立應答訊息,使用Message.reply()方法。這個方法組態一個新的訊息與適當的收件人和主題。該方法接受一個布林引數,指示是否只回復給傳送者 (false)或回復給所有人(true)。

  • 從設定,文字和回復到郵件中,並通過傳輸物件的範例傳送。

  • 關閉傳輸,檔案夾和儲存物件分別。

在這裡,我們使用JangoSMPT伺服器通過該電子郵件傳送到我們的目標電子郵件地址。設定是在環境設定章節解釋。

建立Java類

建立一個Java類檔案ReplyToEmail,是其內容如下:

package com.yiibai;

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 andactivation.jar 在 classpath 中。執行下面的命令從命令提示字元編譯類(兩個罐子被放置在 /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 Reply Email