目录

JavaMail - 回复电子邮件( Replying Emails)

在本章中,我们将了解如何使用JavaMail API回复电子邮件。 以下程序中遵循的基本步骤是:

  • 在属性中获取具有POP和SMPT服务器详细信息的Session对象。 我们需要POP详细信息来检索消息和SMPT详细信息以发送消息。

  • 创建POP3商店对象并连接到商店。

  • 创建文件夹对象并在邮箱中打开相应的文件夹。

  • 检索邮件。

  • 如果要回复,请仔细检查消息并输入“Y”或“y”。

  • 获取邮件的所有信息(收件人,发件人,主题,内容)。

  • 使用Message.reply()方法构建回复消息。 此方法使用正确的收件人和主题配置新邮件。 该方法采用布尔参数,指示是仅回复发件人(false)还是回复all(true)。

  • 在消息中设置From,Text和Reply-to,并通过Transport对象的实例发送它。

  • 分别关闭Transport,文件夹和存储对象。

在这里,我们使用了JangoSMPT服务器,通过该服务器将电子邮件发送到我们的目标电子邮件地址。 环境设置章节中介绍了该设置

创建Java类 (Create Java Class)

创建一个java类文件ReplyToEmail ,其内容如下:

package com.iowiki;
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", "xyz@gmail.com",
            "*****");//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);来设置调试session.setDebug(true);

编译和运行 (Compile and Run)

现在我们的课已经准备好了,让我们编译上面的类。 我已将类ReplyToEmail.java保存到目录: /home/manisha/JavaMailAPIExercise 。 我们需要在类路径中使用jars javax.mail.jaractivation.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

验证输出 (Verify Output)

您应该在命令控制台上看到以下消息:

From: ABC <abc@gmail.com>
Reply-to: abc@trioteksolutions.com
To: XYZ <xyz@gmail.com>
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回复电子邮件
↑回到顶部↑
WIKI教程 @2018