Chris Chris - 2 years ago 131
Java Question

How to send mail with multiple attachments in java

I have here can send mail with multiple attachment:

Properties props = System.getProperties();
String host = "";
props.put("mail.smtp.starttls.enable", "true");
props.put("", 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 = new MimeBodyPart();

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

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

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) {

Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());

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.

Answer Source

Create a simply 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));

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download