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:
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>
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");
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);
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); }
Finally, set the Multipart
object on the MimeMessage
and send the email:
message.setContent(multipart); Transport.send(message);
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) } }
MessagingException
, which can be thrown in various steps.qtablewidget sql-server-ce android-recyclerview subscribe netsh paypal email-attachments spp opencart react-router-v4