个性化阅读
专注于IT技术分析

用Java删除电子邮件

在发送, 转发和接收电子邮件时, 我们也可以将其删除。 Message类的setFlag方法用于删除特定消息。

为了更好地理解此示例, 请首先学习使用JavaMail API发送电子邮件的步骤。
为了使用JavaMail API接收或发送电子邮件, 你需要加载两个jar文件:mail.jar activation.jar下载这些jar文件(或)到Oracle网站下载最新版本。

使用JavaMail API删除电子邮件的步骤

删除电子邮件共有5个步骤。他们是:

  1. 获取会话对象
  2. 创建存储对象并连接到当前主机
  3. 创建文件夹对象并打开它
  4. 获取要删除的消息
  5. 使用setFlag方法删除消息

在Java中删除电子邮件的示例

import com.sun.mail.imap.protocol.FLAGS;
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class DeleteMail {

 public static void main(String args[]) throws Exception {

 String user= "sonoojaiswal@srcmini02.com";//change accordingly
 String password="xxxxx";//change accordingly

 //1) get the session object
 Properties properties = System.getProperties();
 Session session = Session.getDefaultInstance(properties);

 //2) create the store object and connect to the current host 
 Store store = session.getStore("pop3");
 store.connect("mail.srcmini02.com", user, password);

 //3) create the folder object and open it
 Folder folder = store.getFolder("inbox");

 if (!folder.exists()) {
 System.out.println("inbox not found");
 System.exit(0);
 }

 folder.open(Folder.READ_WRITE);

 //4) Get the message to delete
 Message[] msg = folder.getMessages();

 //System.out.println((messages.length+1)+" message found");
 for (int i = 0; i < msg.length; i++) {
   System.out.println("--------- " + (i + 1) + "------------");
   String from = InternetAddress.toString(msg[i].getFrom());
 
   if (from != null) {
     System.out.println("From: " + from);
   }

   String replyTo = InternetAddress.toString(
   msg[i].getReplyTo());
   if (replyTo != null) {
    System.out.println("Reply-to: " + replyTo);
   }

   String to = InternetAddress.toString(
   msg[i].getRecipients(Message.RecipientType.TO));
  
   if (to != null) {
    System.out.println("To: " + to);
   }

   String subject = msg[i].getSubject();
   if (subject != null) {
    System.out.println("Subject: " + subject);
   }
   Date sent = msg[i].getSentDate();
   if (sent != null) {
    System.out.println("Sent: " + sent);
   }
   System.out.println("Message : ");
   System.out.println(msg[i].getContent());

 }//end of for loop

  // get the message number to delete (optional)
  System.out.println("Enter message number to delete :");
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  String no = br.readLine();
  //5) delete the message using setFlag method
  msg[Integer.parseInt(no) - 1].setFlag(FLAGS.Flag.DELETED, true);
  
  System.out.println("Message Deleted .....");

  folder.close(true);
  store.close();
  }
}

如上例所示, 我们能够从用户邮箱中删除电子邮件。现在通过以下方式运行该程序:

加载jar文件 c:\> set classpath = mail.jar; activation.jar;。;
编译源文件 c:\> javac DeleteMail.java
run by c:\> Java DeleteMail
赞(0)
未经允许不得转载:srcmini » 用Java删除电子邮件

评论 抢沙发

评论前必须登录!