How to attach multiple files to an email using JavaMail?

How to attach multiple files to an email using JavaMail?

To attach multiple files to an email using JavaMail, you'll need to use MimeBodyPart to create separate parts for each file attachment, and then add these parts to a Multipart object. Here's a step-by-step guide on how to do this:

Step 1: Add JavaMail Dependency

First, ensure you have the JavaMail dependency in your project. If you're using Maven, add this to your pom.xml:

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>javax.mail-api</artifactId>
    <version>1.6.2</version>
</dependency>

Step 2: Create a Mail Session and MimeMessage

Create a Session and MimeMessage object:

Properties props = new Properties();
props.put("mail.smtp.host", "smtp.yourhost.com"); // replace with your SMTP host
// set other properties as needed

Session session = Session.getInstance(props);
MimeMessage message = new MimeMessage(session);

message.setFrom(new InternetAddress("your-email@example.com"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress("recipient@example.com"));
message.setSubject("Email with Multiple Attachments");

Step 3: Create a Multipart Object and Add Body Part

Create a Multipart object to hold the different parts of the email (body, attachments):

Multipart multipart = new MimeMultipart();

Add the email body:

MimeBodyPart textPart = new MimeBodyPart();
textPart.setText("This is the email body.");

multipart.addBodyPart(textPart);

Step 4: Add Attachments

For each file you want to attach, create a new MimeBodyPart, attach the file, and add it to the Multipart:

String[] attachments = { "path/to/first/file.txt", "path/to/second/file.jpg" }; // paths to files

for (String filePath : attachments) {
    MimeBodyPart filePart = new MimeBodyPart();
    DataSource source = new FileDataSource(filePath);
    filePart.setDataHandler(new DataHandler(source));
    filePart.setFileName(new File(filePath).getName());

    multipart.addBodyPart(filePart);
}

Step 5: Send the Email

Finally, set the Multipart object on the MimeMessage and send the email:

message.setContent(multipart);
Transport.send(message);

Complete Code

Putting it all together, here is how the complete code might look:

import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

// ... (imports)

public class EmailWithAttachments {
    public static void main(String[] args) throws MessagingException {
        // Step 1: Create a Mail Session and MimeMessage
        // Step 2: Create a Multipart Object and Add Body Part
        // Step 3: Add Attachments
        // Step 4: Send the Email
        // (Implement steps as shown above)
    }
}

Notes

  • Replace SMTP host, port, and other properties with appropriate values for your email server.
  • For sending emails through services like Gmail, you might need to enable "less secure apps" or use OAuth 2.0 authentication.
  • The paths to the files should be absolute or relative to the working directory of your Java application.
  • Make sure you handle exceptions appropriately, especially MessagingException, which can be thrown in various steps.

More Tags

qtablewidget sql-server-ce android-recyclerview subscribe netsh paypal email-attachments spp opencart react-router-v4

More Java Questions

More Biochemistry Calculators

More Statistics Calculators

More Pregnancy Calculators

More Dog Calculators