5/7/11

How to Send an Email With Attachments in Java

Sun Microsystems has released the optional JavaMail library to extend its Java programming language. This library makes it far easier for Java developers to create their own email clients and servers. It is a full-featured library and includes support for sending emails with attachments.
    • 1

      Open your favorite text editor or Java development environment.

    • 2

      Paste the following at the top of your Java file to import the JavaMail library:

      import javax.mail.*;

    • 3

      Paste the following to create a new email:

      Session session = Session.getDefaultInstance(System.getProperties(), new PopupAuthentication());

      Message email = new Mimessage(session);

      email.setFrom(new InternetAddress("myemail@email.com));

      email.addRecipient(Message.RecipientType.TO, new InternetAddress("destination@server.com"));

      email.setSubject("A test email.");

      Multipart multipart = new MimeMultipart();

      BodyPart body = new MimeBodyPart();

      body.setText("This is the body of the email.");

      multipart.addBodyPart(body);

      BodyPart attachment = new MimeBodyPart();

      attachment.setDataHandler(new DataHandler(new FileDataSource("file.dat")));

      attachment.setFileName("file.dat");

      multipart.addBodyPart(attachment);

      email.setContent(multipart);

      Transport.send(message);

      This code will send a short email with the attached file "file.dat" to the address "destination@server.com." The email has several parts. Since it has attachments, it must use the "MimeMultipart" class as the parent for all email contents. The body text is added to this, and then the attachment. Finally, the "MimeMultipart" itself is added to the email and the email is sent using the "Transport" class.

  • No comments: