Skip to content

Instantly share code, notes, and snippets.

@trung
Created December 3, 2010 01:55
Show Gist options
  • Save trung/726458 to your computer and use it in GitHub Desktop.
Save trung/726458 to your computer and use it in GitHub Desktop.
How to build/read attachment part using JavaMail in GAE
class Attachment {
public byte[] data;
public String fileName;
public String contentType;
public Attachment(String fileName, byte[] data, String contentType) {
this.data = data;
this.fileName = fileName;
int id = contentType.indexOf(";");
this.contentType = id > -1 ? contentType.substring(0, id) : contentType;;
}
public int getFileSize() {
return data == null ? -1 : data.length;
}
}
byte[] attachmentData = ...;
String attachmentContentType = ...;
String attachmentFileName = ...;
MimeBodyPart attachmentPart = new MimeBodyPart();
attachmentPart.setFileName(attachmentFileName);
attachmentPart.setDisposition(Part.ATTACHMENT);
DataSource src = new ByteArrayDataSource(attachmentData, attachmentContentType);
DataHandler handler = new DataHandler(src);
attachmentPart.setDataHandler(handler);
private Attachment getAttachment(BodyPart bodyPart) throws Exception {
String disposition = bodyPart.getDisposition();
if (disposition != null && (disposition.equals(Part.ATTACHMENT) || (disposition
.equals(Part.INLINE)))) {
InputStream attachmentInputStream = null;
try {
attachmentInputStream = bodyPart.getInputStream();
byte[] data = getBytesFromInputStream(attachmentInputStream);
return new Attachment(bodyPart.getFileName(), data, bodyPart.getContentType());
} finally {
try {
if (attachmentInputStream != null)
attachmentInputStream.close();
} catch (Exception e) {
}
}
}
return null;
}
public byte[] getBytesFromInputStream(InputStream inputStream) throws IOException {
BufferedInputStream bis = null;
ByteArrayOutputStream bos = null;
try {
bis = new BufferedInputStream(inputStream);
// write it to a byte[] using a buffer since we don't know the exact
// image size
byte[] buffer = new byte[1024];
bos = new ByteArrayOutputStream();
int i = 0;
while (-1 != (i = bis.read(buffer))) {
bos.write(buffer, 0, i);
}
byte[] data = bos.toByteArray();
return data;
} catch (IOException e) {
throw e;
} finally {
try {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
} catch (IOException e) {
// ignore
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment