我需要从GMail获取附件并将其上传到Amazon S3。
我正在使用 imap ,以连接到GMail并能够访问附件, 使用javax.mail.internet.MimeBodyPart,它提供了Base64DecoderStream中的getInputStream(),而不是FileInputStream或ByteArray输入流。 由于我的文件是二进制文件(如.zip)。
我需要InputStream将其上传到S3。
那么如何将Base64DecoderStream转换为InputStream?
public void processMails() {
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
Session session = null;
Store store = null;
session = Session.getInstance(props, null);
Folder inboxFolder;
try {
store = session.getStore();
store.connect("imap.gmail.com", "test@gmail.com", "password");
inboxFolder = store.getFolder("INBOX");
inboxFolder.open(Folder.READ_WRITE);
Message messages[] = inboxFolder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
for (Message msg : messages) {
try {
Multipart multiPart = (Multipart)msg.getContent();
for (int i = 0; i < multiPart.getCount(); i++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(i);
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
InputStream stream = null;// need to convert part.getInputStream() to InputStream
processAttachment(stream);
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
//上传功能如下:
public void processAttachment(InputStream asset) {
ObjectMetadata meta = new ObjectMetadata();
if (asset instanceof FileInputStream) {
meta.setContentLength(((FileInputStream)asset).available());
} else if (asset instanceof ByteArrayInputStream) {
meta.setContentLength(((ByteArrayInputStream)asset).available());
}
else {
meta.setContentLength(asset.available());
}
s3.putObject(new PutObjectRequest(bucket, "parentfolder/subfolder/abc.zip", asset, meta));
}
答案 0 :(得分:1)
如果您需要整个msg来播放流。
ByteArrayOutputStream bos = new ByteArrayOutputStream();
msg.writeTo(bos);
bos.close();
InputStream in = new ByteArrayInputStream(bos.toByteArray());
如果您只需要内容尝试此
InputStream base64InputStream = (InputStream) part.getInputStream();
int i = 0;
byte[] byteArray = new byte[base64InputStream.available()];
while ((i = (int) ((InputStream) base64InputStream).available()) > 0) {
int result = (int) (((InputStream) base64InputStream).read(byteArray));
if (result == -1)
break;
}
InputStream inputStream = new ByteArrayInputStream(byteArray);