Creating an email containing attachments using JavaMail

This simple example creates an .eml file (which you can open with eg. Outlook Express) containing the file c:autoexec.bat as an attachment.

Creating an attachment with JavaMail is simple: pass a DataSource instance to the constructor of DataHandler and add it to a MimeBodyPart. Add all the MimeBodyParts to a Multipart instance and initialize the message with it.

Main.java:

import javax.activation.*;
import javax.mail.internet.*;
import javax.mail.*;
import java.io.*;
 
public class Main
{
   public static void main(String []args) throws Exception {
      Message message = new MimeMessage((Session) null);
      message.setFrom(new InternetAddress("source@source.com"));
      message.addRecipient(Message.RecipientType.TO, new InternetAddress("dest@dest.com"));
      message.setSubject("JavaMail attachment test");
 
      // create a multipart instance
      Multipart multipart = new MimeMultipart();
 
      // create the body of the email 
      BodyPart bodyPart = new MimeBodyPart();
      bodyPart.setText("Body of email");      
      multipart.addBodyPart(bodyPart);
 
      // create a file attachment
      bodyPart = new MimeBodyPart();
      DataSource source = new FileDataSource("c:\autoexec.bat");
      bodyPart.setDataHandler(new DataHandler(source));
      // remember the name of the file
      bodyPart.setFileName("autoexec.bat");
      multipart.addBodyPart(bodyPart);
 
      message.setContent(multipart);
 
      // write it to an .eml file [or send it with Transport.send(message) ]
      message.writeTo(new BufferedOutputStream(new FileOutputStream("test.eml")));
   }
}