How to attach multiple files to an email using JavaMail? How to attach multiple files to an email using JavaMail? java java

How to attach multiple files to an email using JavaMail?


Well, it's been a while since I've done JavaMail work, but it looks like you could just repeat this code multiple times:

DataSource source = new FileDataSource(filename);messageBodyPart.setDataHandler(new DataHandler(source));messageBodyPart.setFileName(filename);multipart.addBodyPart(messageBodyPart);

For example, you could write a method to do it:

private static void addAttachment(Multipart multipart, String filename){    DataSource source = new FileDataSource(filename);    BodyPart messageBodyPart = new MimeBodyPart();            messageBodyPart.setDataHandler(new DataHandler(source));    messageBodyPart.setFileName(filename);    multipart.addBodyPart(messageBodyPart);}

Then from your main code, just call:

addAttachment(multipart, "file1.txt");addAttachment(multipart, "file2.txt");

etc


    Multipart mp = new MimeMultipart();        MimeBodyPart mbp1 = new MimeBodyPart();        mbp1.setContent(body,"text/html");        mp.addBodyPart(mbp1);        if(filename!=null)        {            MimeBodyPart mbp2 = null;            FileDataSource fds =null;            for(int counter=0;counter<filename.length;counter++)            {                mbp2 = null;                fds =null;                mbp2=new MimeBodyPart();                fds = new FileDataSource(filename[counter]);                mbp2.setDataHandler(new DataHandler(fds));                mbp2.setFileName(fds.getName());                mp.addBodyPart(mbp2);            }        }        msg.setContent(mp);        msg.setSentDate(new Date());        Transport.send(msg);