Retrieve attachment
I'm using this code to retrieve email with a simple txt file as attachment:
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("pop3");
store.connect(host, username, password);
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
Message message = folder.getMessage(1);
Multipart multipart = (Multipart) message.getContent();
// Process each part of the message
for (int i=0; i<multipart.getCount(); i++) {
processPart(multipart.getBodyPart(i));
}
folder.close(false);
store.close();
}
catch (MessagingException me) {
System.err.println(me.getMessage());
}
catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
catch(ClassCastException e)
{
System.err.println(e.getMessage());
}
}
private static void processPart(Part part)
throws MessagingException, IOException{
String disposition = part.getDisposition();
String fileName = part.getFileName();
if (disposition.equals(Part.ATTACHMENT)) {
// Its an attachment
if (fileName == null) {
// the file name is null, so assign a name
fileName = File.createTempFile("attachment", ".txt").getName();
}
// write the part to a file
writeFile(fileName, part.getInputStream());
}
else {
// the disposition is either INLINE or null
}
}
private static void writeFile
(String fileName, InputStream in) throws IOException {
// Do no overwrite existing file
File file = new File(fileName);
for (int i=0; file.exists(); i++) {
file = new File(fileName+i);
}
// Write the part to file
BufferedOutputStream bos =
new BufferedOutputStream(new FileOutputStream(file));
BufferedInputStream bis = new BufferedInputStream(in);
int aByte;
while ((aByte = bis.read()) != -1) {
bos.write(aByte);
}
bos.flush();
bos.close();
bis.close();
}
I'm getting the same output all over again :"java.lang.String cannot be cast to javax.mail.Multipart".What am I doing wrong?>

