JavaMail API - Email trả lời

Trong chương này, chúng ta sẽ xem cách trả lời email bằng JavaMail API. Các bước cơ bản được thực hiện trong chương trình dưới đây là:

  • Lấy đối tượng Session với chi tiết máy chủ POP và SMPT trong thuộc tính. Chúng tôi sẽ cần chi tiết POP để truy xuất tin nhắn và chi tiết SMPT để gửi tin nhắn.

  • Tạo đối tượng cửa hàng POP3 và kết nối với cửa hàng.

  • Tạo đối tượng Thư mục và mở thư mục thích hợp trong hộp thư của bạn.

  • Lấy tin nhắn.

  • Lặp lại các tin nhắn và nhập "Y" hoặc "y" nếu bạn muốn trả lời.

  • Nhận tất cả thông tin (Đến, Từ, Chủ đề, Nội dung) của thư.

  • Tạo tin nhắn trả lời, sử dụng phương thức Message.reply (). Phương thức này định cấu hình một Thư mới với người nhận và chủ đề thích hợp. Phương thức nhận tham số boolean cho biết chỉ trả lời người gửi (sai) hay trả lời tất cả (đúng).

  • Đặt Từ, Văn bản và Trả lời trong tin nhắn và gửi nó thông qua phiên bản của đối tượng Vận chuyển.

  • Đóng các đối tượng Truyền tải, thư mục và lưu trữ tương ứng.

Ở đây chúng tôi đã sử dụng máy chủ JangoSMPT mà qua đó các email được gửi đến địa chỉ email đích của chúng tôi. Thiết lập được giải thích trong chương Thiết lập Môi trường .

Tạo lớp Java

Tạo tệp lớp java ReplyToEmail, nội dung của nó như sau:

package com.tutorialspoint;

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();
      }

   }

}
Bạn có thể bật gỡ lỗi bằng cách bỏ ghi chú câu lệnh session.setDebug (true);

Biên dịch và Chạy

Bây giờ lớp của chúng ta đã sẵn sàng, chúng ta hãy biên dịch lớp trên. Tôi đã lưu lớp ReplyToEmail.java vào thư mục:/home/manisha/JavaMailAPIExercise. Chúng tôi cần các chum javax.mail.jaractivation.jar trong classpath. Thực thi lệnh bên dưới để biên dịch lớp (cả hai lọ đều được đặt trong thư mục / home / manisha /) từ dấu nhắc lệnh:

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

Bây giờ lớp đã được biên dịch, hãy thực thi lệnh sau để chạy:

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

Xác minh đầu ra

Bạn sẽ thấy thông báo sau trên bảng điều khiển lệnh:

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 ....

Kiểm tra hộp thư đến mà thư đã được gửi đến. Trong trường hợp của chúng tôi, thông báo nhận được trông như sau: