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

用Java接收电子邮件

点击下载

为了接收电子邮件, 将Store和Folder类与MimeMessage, Session和Transport类配合使用。

为了更好地理解此示例, 请首先学习使用JavaMail API发送电子邮件的步骤。

要使用JavaMail API发送电子邮件, 你需要加载两个jar文件:

  • mail.jar
  • activation.jar

下载这些jar文件

(或)访问Oracle网站以下载最新版本。


使用JavaMail API接收电子邮件的步骤

使用JavaMail API接收电子邮件有5个步骤。他们是:

  1. 获取会话对象
  2. 创建POP3存储对象并与弹出服务器连接
  3. 创建文件夹对象并打开它
  4. 从数组中的文件夹中检索消息并打印
  5. 关闭存储和文件夹对象

用Java接收电子邮件的示例

让我们看一下使用java mail api接收邮件的示例。

import java.io.IOException;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import com.sun.mail.pop3.POP3Store;

public class ReceiveMail{

 public static void receiveEmail(String pop3Host, String storeType, String user, String password) {
  try {
   //1) get the session object
   Properties properties = new Properties();
   properties.put("mail.pop3.host", pop3Host);
   Session emailSession = Session.getDefaultInstance(properties);
   
   //2) create the POP3 store object and connect with the pop server
   POP3Store emailStore = (POP3Store) emailSession.getStore(storeType);
   emailStore.connect(user, password);

   //3) create the folder object and open it
   Folder emailFolder = emailStore.getFolder("INBOX");
   emailFolder.open(Folder.READ_ONLY);

   //4) retrieve the messages from the folder in an array and print it
   Message[] messages = emailFolder.getMessages();
   for (int i = 0; i < messages.length; i++) {
	Message message = messages[i];
	System.out.println("---------------------------------");
	System.out.println("Email Number " + (i + 1));
	System.out.println("Subject: " + message.getSubject());
	System.out.println("From: " + message.getFrom()[0]);
	System.out.println("Text: " + message.getContent().toString());
   }

   //5) close the store and folder objects
   emailFolder.close(false);
   emailStore.close();

  } catch (NoSuchProviderException e) {e.printStackTrace();} 
  catch (MessagingException e) {e.printStackTrace();}
  catch (IOException e) {e.printStackTrace();}
 }

 public static void main(String[] args) {

  String host = "mail.srcmini02.com";//change accordingly
  String mailStoreType = "pop3";
  String username= "sonoojaiswal@srcmini02.com";
  String password= "xxxxx";//change accordingly

  receiveEmail(host, mailStoreType, username, password);

 }
}

如你在上面的示例中看到的, 需要对用户标识和密码进行身份验证。如该程序所示, 你可以轻松接收电子邮件, 但可以相应地更改用户名和密码。让我们看看如何通过简单的技术再次运行它:

加载jar文件 c:\> set classpath = mail.jar; activation.jar;。;
编译源文件 c:\> javac ReceiveMail.java
由……运营 c:\> Java Receivemail
赞(0)
未经允许不得转载:srcmini » 用Java接收电子邮件

评论 抢沙发

评论前必须登录!