我试图使用Mandrill Wrapper for Java将文件附加到电子邮件中。这是我的代码片段正在处理附件文件。
public byte[] attachmentContent(String filepath)
{
Path path = Paths.get(filepath);
byte[] data = null;
try {
data = Files.readAllBytes(path);
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
//adding attachment
ArrayList<MandrillAttachment> attachedFiles = new ArrayList<MandrillAttachment>();
//file 1
String attType = "application/pdf";
String attName = "Indian License.pdf";
String attContent = Base64.encodeBase64URLSafeString(attachmentContent("C:\\LL Indian License.pdf"));
System.out.println(attContent);
//attach
attachedFiles.add(new MandrillAttachment(attType, attName, attContent));
message.setAttachments(attachedFiles);
但是,文件在发送过程中一直存在损坏。关于如何解决这个问题的任何想法?
答案 0 :(得分:1)
(这可能为时已晚)无法使用Base64使用正确的编码来避免此问题。我使用以下代码来解决问题。
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.codec.binary.Base64;
List<MessageContent> listofAttachments = new ArrayList<MessageContent>();
MessageContent attachment = new MessageContent();
attachment.setType("application/pdf");
attachment.setName("Test.pdf");
File file = new File("C:\\Users\\xxx\\PdfTesting\\Test.pdf");
InputStream is = new FileInputStream(file);
long length = file.length();
if (length > Integer.MAX_VALUE) {
// File is too large
}
byte[] bytes = new byte[(int) length];
int offset = 0;
int numRead = 0;
while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}
if (offset < bytes.length) {
throw new IOException("Could not completely read file " + file.getName());
}
is.close();
byte[] encoded = Base64.encodeBase64(bytes);
String encodedString = new String(encoded);
attachment.setContent(encodedString);