I have 2 files in the directory “bar” for testing. from the code below, it is suppose to send all files in that directory as email attachments. The problem is that when I send them, I get duplicates of one file in my email. I did have it working correctly once before for testing, but I dont remember what I might have changed.
Does anyone recognize what might be wrong with my code or why I instead of sending all the files in the directory, I get one file multiple times in my email?
Here is my code:
multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
File f = new File("C:\\foo\\bar");
File[] attachments = f.listFiles();
//email with attachments (if any)
for(int i = 0; i < f.listFiles().length - 1; i++){
DataSource fileDataSource = new FileDataSource(attachments[i]);
messageBodyPart.setDataHandler(new DataHandler(fileDataSource));
messageBodyPart.setFileName(attachments[i].getName());
multipart.addBodyPart(messageBodyPart);
}
message.setContent(multipart);
message.setSentDate(new Date());
Transport.send(message);
You have an off-by-one error: you want the loop to be either
or
You also have two lines that say
which is why you have the bodypart containing the first file twice.