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.

import javax.activation.*;
import javax.mail.internet.*;
import javax.mail.*;
public class Main
   public static void main(String []args) throws Exception {
      Message message = new MimeMessage((Session) null);
      message.setFrom(new InternetAddress(""));
      message.addRecipient(Message.RecipientType.TO, new InternetAddress(""));
      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");      
      // 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
      // write it to an .eml file [or send it with Transport.send(message) ]
      message.writeTo(new BufferedOutputStream(new FileOutputStream("test.eml")));