Take the 2-minute tour ×

I have a byte array wich i wish to add as an attachement to an email i am sending.

Unfortunally i can't find how to attach it as a byte array, the solution i have uses disk files (which i dont want since i dont want to write the byte array just so i can attach it).

I've found one solution that involves creating an object that extends DataSource and use this as a wrapper for the byte array and then feed that to the MimeBodyPart.

Anyone know of a better solution?

share|improve this question

2 Answers 2

up vote 12 down vote accepted

Creating a DataSource is the right approach. You don't have to write your own, though. Just use the ByteArrayDataSource from JavaMail.

share|improve this answer
/facepalm i dont know why i didnt see that class, especially considering i was trying to use the other solution and i wrote the class down and named it : ByteArrayDatasource. =S –  Nuno Furtado Nov 26 '09 at 17:45
@NunoFurtado Can you maybe update your question with a code snippet that works? –  snooze92 Jan 31 '14 at 10:08
@snooze92 sorry this took so long, here is a pastebin of it –  Nuno Furtado Feb 6 '14 at 16:57

Here is the code for your requirement...store attachment file as BLOB in DB and fetch that for sending it as a attachment in mail...............

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

public class BufferedDataSource implements DataSource { 

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

public BufferedDataSource(byte[] data, String name) { 
_data = data; 
_name = name;

public String getContentType() { return "application/octet-stream";} 
public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(_data);} 
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;
//Getting ByteArray From 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(); 
//Attach File for mail
MimeBodyPart att = new MimeBodyPart(); 
BufferedDataSource bds = new BufferedDataSource(bytearray, "AttName"); 
att.setDataHandler(new DataHandler(bds)); 
share|improve this answer

Your Answer


