用Java接收带有附件的电子邮件

收到电子邮件后, 我们还可以使用JavaMail API中的Multipart和BodyPart类来接收附件。
为了更好地理解此示例, 请首先学习使用JavaMail API发送电子邮件的步骤。
为了使用JavaMail API接收或发送电子邮件, 你需要加载两个jar文件:

  • mail.jar
  • activation.jar
【用Java接收带有附件的电子邮件】下载这些jar文件
(或)访问Oracle网站以下载最新版本。

用Java接收带有附件的电子邮件的示例
import java.util.*; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; import java.io.*; class ReadAttachment{ public static void main(String [] args)throws Exception{String host="mail.srcmini.com"; final String user="sonoojaiswal@srcmini.com"; final String password="xxxxx"; //change accordinglyProperties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host ); properties.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, password); } }); Store store = session.getStore("pop3"); store.connect(host, user, password); Folder folder = store.getFolder("inbox"); folder.open(Folder.READ_WRITE); Message[] message = folder.getMessages(); for (int a = 0; a < message.length; a++) { System.out.println("-------------" + (a + 1) + "-----------"); System.out.println(message[a].getSentDate()); Multipart multipart = (Multipart) message[a].getContent(); for (int i = 0; i < multipart.getCount(); i++) { BodyPart bodyPart = multipart.getBodyPart(i); InputStream stream = bodyPart.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(stream)); while (br.ready()) { System.out.println(br.readLine()); } System.out.println(); } System.out.println(); }folder.close(true); store.close(); } }

加载jar文件 c:\> set classpath = mail.jar; activation.jar; 。;
编译源文件 c:\> javac ReadAttachment.java
由… … 运营 c:\> Java ReadAttachment

    推荐阅读