4

I have here can send mail with multiple attachment:

Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");

Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
Multipart multipart = new MimeMultipart();

// creates body part for the message
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "text/html");

//set message body
BodyPart msgBodyPart = new MimeBodyPart();
msgBodyPart.setText(body);
multipart.addBodyPart(msgBodyPart);
msgBodyPart = new MimeBodyPart();

//attach file
DataSource source = new FileDataSource(attachFile);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(attachFile);
multipart.addBodyPart(messageBodyPart);

//attach file 2
source = new FileDataSource(attachFile2);
BodyPart messageBodyPart2 = new MimeBodyPart();
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(attachFile2);
multipart.addBodyPart(messageBodyPart2);

try {
    message.setFrom(new InternetAddress(from));
    InternetAddress[] toAddress = new InternetAddress[to.length];

      // To get the array of addresses
    for( int i = 0; i < to.length; i++ ) {
        toAddress[i] = new InternetAddress(to[i]);
    }

    for( int i = 0; i < toAddress.length; i++) {
        message.addRecipient(Message.RecipientType.TO, toAddress[i]);
    }
} catch (MessagingException ex) {
    ex.printStackTrace();
}

message.setSubject(subject);
message.setContent(multipart);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();

But the problem is how can I add multiple attachments? I don't know if i can declare many variable or put it on array. The code can only include 2 attachments what if 5 or any in every send of the email.

Chris
  • 45
  • 1
  • 1
  • 4
  • 3
    Here's a whacked out idea. Create a method called something like `attach`, which takes a `File` and a `Multipart` as parameters. Call it as many times as you like and see what happens :) – MadProgrammer Feb 24 '15 at 03:06
  • Do you know how Java works? (Specifically, how variables, objects and arrays work). If you do, it should be easy to see how to attach an array of files. – user253751 Feb 24 '15 at 03:11

3 Answers3

6

Create a simple method called, something like, attachFile, which takes a File, Multipart and MimeBodyPart as parameters...

public void attachFile(File file, Multipart multipart, MimeBodyPart messageBodyPart) {
    DataSource source = new FileDataSource(file);
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(file.getName());
    multipart.addBodyPart(messageBodyPart);    
}

Call it as often as you need

File attachFiles[] = ...

if (attachFiles > 0) {
    //attach file
    attachFile(attachFiles[0], multipart, messageBodyPart);
    if (attachFiles > 1) {
        for (int index = 1; index < attachFiles.length; index++) {
            attachFile(attachFiles[0], multipart, new MimeBodyPart());
        }
    }
}

as an example

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Thanks for your answer on this post. I tried to apply this to attach a couple of files to a single email. I used the same attachFile method you posted except I took the first argument as a `String filename` instead of `File file`. I tried to attach bothe the files using `attachFile("extract_emails.csv",multipart,messageBodyPart); attachFile("Compare.txt",multipart,messageBodyPart);` there were no errors but I see that the compare.txt has been attached twice to the mail and extract_emails hasn't been attached at all. Not sure where I am going wrong. @MadProgrammer – Hemanth Annavarapu Jun 21 '17 at 16:44
  • @HemanthAnnavarapu add a line of code "messageBodyPart = new MimeBodyPart();" directly before the method call setDataHandler, that will fix this – Conor Mar 03 '20 at 14:55
3

Using Java Mail 1.4 and above makes attaching file more simpler,

MimeBodyPart messageBodyPart = new MimeBodyPart();

messageBodyPart.attachFile(String filePath)

multipart.addBodyPart(messageBodyPart);
akashdeep-mishra
  • 343
  • 4
  • 19
2

Have a look at answer given here

https://stackoverflow.com/a/3177640/772590

Step 1 Create a Datasource

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

Step 2 create method to add attachment

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);
}

Step 3 call above method to add attachment

addAttachment(multipart, "file1.txt");
addAttachment(multipart, "file2.txt");
Community
  • 1
  • 1
Santosh Joshi
  • 3,290
  • 5
  • 36
  • 49