How do I attach a database BLOB into a mail message, and send by invoking Java classes from SQL procedures (in Oracle)?

Denis Navarre

Here is a solution (for Oracle):

1. Create a class BufferedDataSource to transform a byte array into a DataSource used to attach the "stream" to the message.
2. Convert the BLOB (here is a BLOB from Oracle) into a byte array to be used in the DataSource
3. Attach the stream through the DataSource

Create a BufferedDataSource to be used to attach the file:

package lu.ic.visitcard.mail;

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

* DataSource from an array of bytes
* Creation date: (07/06/01 21:22:30)
public class BufferedDataSource implements DataSource {

private byte[] _data;
private java.lang.String _name;

* Creates a DataSource from an array of bytes
* @param data byte[] Array of bytes to convert into a DataSource
* @param name String Name of the DataSource (ex: filename)
public BufferedDataSource(byte[] data, String name) {
_data = data;
_name = name;


* Returns the content-type information required by a DataSource
* application/octet-stream in this case
public String getContentType() {
return "application/octet-stream";


* Returns an InputStream from the DataSource
* @returns InputStream Array of bytes converted into an InputStream
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(_data);


* Returns the name of the DataSource
* @returns String Name of the DataSource
public String getName() {
return _name;


* Returns an OutputStream from the DataSource
* @returns OutputStream Array of bytes converted into an OutputStream
public OutputStream getOutputStream() throws IOException {
OutputStream out = new ByteArrayOutputStream();
return out;



How to get a byte array from a BLOB:

byte[] bytearray;
BLOB blob = ((OracleResultSet) rs).getBLOB("IMAGE_GIF");
if (blob != null) {

BufferedInputStream bis = new BufferedInputStream(blob.getBinaryStream());
ByteArrayOutputStream bao = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int length = 0;
while ((length = bis.read(buffer)) != -1) {
bao.write(buffer, 0, length);

bytearray = bao.toByteArray();


How to attach the file:

// Create attachment zone
MimeBodyPart att = new MimeBodyPart();
// Attach the file or buffer
BufferedDataSource bds = new BufferedDataSource(bytearray, "AttName");
att.setDataHandler(new DataHandler(bds));