Send mailbox using byte [] using Java-Mail

I have an array of bytes that I want to add as an attachment to the email I'm sending.

Unfortunately, I cannot find how to attach it as an array of bytes. In the solution, I have files on the disk (which I do not need, since I do not want to write an array of bytes so that I can attach it).

I found one solution that involves creating an object that extends the DataSource and uses it as a wrapper for an array of bytes, and then passes it to MimeBodyPart.

Does anyone know of a better solution?

+4
source share
2 answers

Creating a DataSource is the right approach. However, you do not need to write your own. Just use ByteArrayDataSource from JavaMail.

+17
source

Here is the code for your requirement ... save the attachment file as a BLOB in the database and extract it to send it as an attachment by 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(); out.write(_data); 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); } bao.close(); bis.close(); bytearray = bao.toByteArray(); } =============================================================== //Attach File for mail MimeBodyPart att = new MimeBodyPart(); BufferedDataSource bds = new BufferedDataSource(bytearray, "AttName"); att.setDataHandler(new DataHandler(bds)); att.setFileName(bds.getName()); 
+1
source

All Articles