2009-11-26 73 views
4

我有一個字節數組,我希望作爲附件添加到我發送的電子郵件。發送電子郵件附加使用Java的郵件使用字節[]

不幸的是我找不到如何將它作爲一個字節數組附加,解決方案我使用磁盤文件(我不想要,因爲我不想寫字節數組,所以我可以附上它)。

我發現了一個解決方案,涉及到創建一個擴展DataSource的對象,並將其用作字節數組的包裝,然後將其提供給MimeBodyPart。

任何人都知道更好的解決方案?

回答

17

創建DataSource是正確的方法。不過,你不必自己寫。只需使用JavaMail的ByteArrayDataSource即可。

+1

/facepalm我不知道爲什麼我沒有看到這個類,尤其是考慮到我正在嘗試使用其他解決方案,並且我寫下了該類並將其命名爲:ByteArrayDatasource。 = S – 2009-11-26 17:45:46

+0

@NunoFurtado你可以用一個可用的代碼片段來更新你的問題嗎? – snooze92 2014-01-31 10:08:52

+0

@ snooze92對不起,這花了這麼長時間,這裏是一個[pastebin](http://pastebin.com/BbYUAC6u)它 – 2014-02-06 16:57:04

1

這是給你的要求的代碼...商店附件文件在DB BLOB,獲取該發送它作爲郵件附件...............

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());