我试图使用 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);
但是,文件在发送过程中不断损坏。知道如何解决这个问题吗?
最佳答案
(回答这个问题可能为时已晚)使用 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);
关于java - Mandrill/Java - 附件损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22743770/