How do I attach multiple files to a message?
Created May 7, 2012
John Zukowski You just need to combine them all into one MimeMultipart and add each one as its own MimeBodyPart. The following does just this, taking a directory name as the argument, sending everything within the directory as attachments in one message. Use with care as the program doesn't limit the message size.
import java.util.Properties; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; import java.io.*; public class AttachExample { public static void main (String args[]) throws Exception { String host = args[0]; String from = args[1]; String to = args[2]; String directory = args[3]; Properties props = System.getProperties(); props.put("mail.smtp.host", host); Session session = Session.getInstance(props, null); Message message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("Directory Attachments"); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText("Directory: " + directory); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); File dir = new File(directory); String list[] = dir.list(); for (int i=0, n=list.length; i<n; i++) { File f = new File(list[i]); if (f.isFile()) { System.out.println("Adding: " + list[i]); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(list[i]); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(list[i]); multipart.addBodyPart(messageBodyPart); } } message.setContent(multipart); Transport.send(message); } }