我正在使用 java 邮件阅读电子邮件附件。这是我使用的代码:
public static void main(String args[]) throws Exception {
String host = "172.16.0.186";
String user = "admin";
String password = "1234";
// Get system properties
Properties properties = System.getProperties();
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
// Get a Store object that implements the specified protocol.
Store store = null;
try {
store = session.getStore("pop3");
//Connect to the current host using the specified username and password.
store.connect(host, user, password);
} catch (Exception e) {
logger.warn("An exception occured," + e);
}
//Create a Folder object corresponding to the given name.
Folder folder = store.getFolder("Inbox");
// Open the Folder.
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++) {
//System.out.println(i);
//System.out.println(multipart.getContentType());
BodyPart bodyPart = multipart.getBodyPart(i);
InputStream stream = bodyPart.getInputStream();
File file = new File("C:\\Attachments\\" + bodyPart.getFileName());
BufferedReader br = new BufferedReader(
new InputStreamReader(stream));
while (br.ready()) {
System.out.println(br.readLine());
}
saveFile(bodyPart.getFileName(), stream);
attachments.add(file);
System.out.println();
}
System.out.println();
}
folder.close(true);
store.close();
}
/**
* Save file.
*
* @param filename
* the filename
* @param input
* the input
*/
public static void saveFile(String filename, InputStream input) {
System.out.println(filename);
try {
if (filename == null) {
//filename = File.createTempFile("VSX", ".out").getName();
return;
}
// Do no overwrite existing file
filename = "C:\\Attachments\\" + filename;
File file = new File(filename);
for (int i = 0; file.exists(); i++) {
file = new File(filename + i);
}
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
BufferedInputStream bis = new BufferedInputStream(input);
int aByte;
while ((aByte = bis.read()) >= 0) {
bos.write(aByte);
}
bos.flush();
bos.close();
bis.close();
} // end of try()
catch (IOException exp) {
System.out.println("IOException:" + exp);
}
} //end of saveFile()
}
发生以下异常: javax.mail.NoSuchProviderException: pop3
最后一个问题:如果可以使用 java 邮件 API 读取所有文件类型,那么我们如何读取 excel 文件、HTML 文件或 word 文件。