在base64的javamail中附加大文件
Attach large files in javamail in base64
目前我在邮件中附加文件(小)如下:
byte[] byteArray = IOUtils.toByteArray(new FileInputStream(file));
MimeBodyPart messageBodyPart = new PreencodedMimeBodyPart("base64");
String contentType = "application/octet-stream";
String base64Content = new String(Base64.encodeBase64(byteArray));
messageBodyPart.setContent(base64Content, contentType);
messageBodyPart.setFileName(MimeUtility.encodeText(attachment.getFileName(),
CharEncoding.UTF_8, null));
messageBodyPart.setDisposition(MimeBodyPart.ATTACHMENT);
multipart.addBodyPart(messageBodyPart);
但是一次将文件读取到 byte[]
不适用于大文件。但最后我想将附件放在电子邮件中的 base64 编码字符串中。那么我该如何处理附件中的大文件呢?
好吧,你可以尝试用它来发送你想要的任何文件。还有任意数量的文件。
/**
Multi part message email
**/
Multipart multipart = new MimeMultipart();
//Add atachments
String[] attachments = new String[2];
attachments[0] = "your_complete_path.pdf";
attachments[1] = "your_complete_path.txt";
if(attachments != null && attachments.length > 0) {
for (String str : attachments) {
MimeBodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(str);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(source.getName());
multipart.addBodyPart(messageBodyPart);
}
}
message.setContent(multipart);
messageBodyPart.attachFile(file, "application/octet-stream", "base64");
文件不会被读入内存,它会在消息发送时被编码"on the fly"。
目前我在邮件中附加文件(小)如下:
byte[] byteArray = IOUtils.toByteArray(new FileInputStream(file));
MimeBodyPart messageBodyPart = new PreencodedMimeBodyPart("base64");
String contentType = "application/octet-stream";
String base64Content = new String(Base64.encodeBase64(byteArray));
messageBodyPart.setContent(base64Content, contentType);
messageBodyPart.setFileName(MimeUtility.encodeText(attachment.getFileName(),
CharEncoding.UTF_8, null));
messageBodyPart.setDisposition(MimeBodyPart.ATTACHMENT);
multipart.addBodyPart(messageBodyPart);
但是一次将文件读取到 byte[]
不适用于大文件。但最后我想将附件放在电子邮件中的 base64 编码字符串中。那么我该如何处理附件中的大文件呢?
好吧,你可以尝试用它来发送你想要的任何文件。还有任意数量的文件。
/**
Multi part message email
**/
Multipart multipart = new MimeMultipart();
//Add atachments
String[] attachments = new String[2];
attachments[0] = "your_complete_path.pdf";
attachments[1] = "your_complete_path.txt";
if(attachments != null && attachments.length > 0) {
for (String str : attachments) {
MimeBodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(str);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(source.getName());
multipart.addBodyPart(messageBodyPart);
}
}
message.setContent(multipart);
messageBodyPart.attachFile(file, "application/octet-stream", "base64");
文件不会被读入内存,它会在消息发送时被编码"on the fly"。