How to send email with attachment in Java

I got the following code from: http://it.toolbox.com/wiki/index.php/Send_Email_with_Attachments_Using_Java

It’s quite useful as I had to use it modified in one of my personal projects… Enjoy:

Introduction

This Article will explain about sending mail with attachments using Java Mail.

Kits: J2sdk, Java Mail Api, JAF API, Smtp server address

Steps

  1. Create src,lib,bin folders. Src directory contains source java files. bin contains the compiled java files. lib contains mail.jar,activation.jar files.
  2. Create a new java program.
  3. Creating Mail Session with server
  4. Creating Subject, Body , Attachments
  5. Sending Mail
  6. Handling Exceptions

Examples

import java.util.*; import java.io.*; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*;

public class AttachExample {

 public static void main (String args[]) throws Exception {
   String host = "smtp.kar.com";
   String from = "FromAddre@kar.com";
   String to[] =  new String[]{"ABC@kar.com","XYZ@kar.com"};
   String filename = "AttachFile.txt";
   // Get system properties
   Properties props = System.getProperties();
   props.put("mail.smtp.host", host);
   Session session = Session.getInstance(props, null);
   System.out.println(session.getProperties());
   Message message = new MimeMessage(session);
   message.setFrom(new InternetAddress(from));

   InternetAddress[] toAddress = new InternetAddress[to.length];
   for (int i = 0; i < to.length; i++)
     toAddress[i] = new InternetAddress(to[i]);
   message.setRecipients(Message.RecipientType.TO, toAddress);
   message.setSubject("Hello JavaMail Attachment");
   BodyPart messageBodyPart = new MimeBodyPart();
   messageBodyPart.setText("Here's the file");
   Multipart multipart = new MimeMultipart();
   multipart.addBodyPart(messageBodyPart);
   messageBodyPart = new MimeBodyPart();
   DataSource source = new FileDataSource(filename);
   messageBodyPart.setDataHandler(new DataHandler(source));
   messageBodyPart.setFileName(filename);
   multipart.addBodyPart(messageBodyPart);
   message.setContent(multipart);
  try{
       Transport.send(message);
  }
  catch(SendFailedException sfe)
   {
 	 message.setRecipients(Message.RecipientType.TO,  sfe.getValidUnsentAddresses());
 	 Transport.send(message);

   }
 }

}

Leave a Reply

You must be logged in to post a comment.