我正在为MimiMultipart编写一种编码器/解码器
编码器:MimiMultipart - >十六进制串
解码器:HexString - > MimiMultipart
此方法为以后的编码创建MimeMultipart:
private MimeMultipart compose_mail(String to, String body) throws Exception{
Document d = XMLConnector.get("body.html");
String html_body = d.html();
MimeMultipart multipart = new MimeMultipart("related");
// Body part
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(html_body, "text/html; charset=\"UTF-8\"");
multipart.addBodyPart(messageBodyPart);
// Image part
File img_file = new File("img/logo.png");
MimeBodyPart messageImgPart = new MimeBodyPart();
messageImgPart.setHeader("Content-Type", "image/jpeg");
messageImgPart.setHeader("Content-ID","<logo>");
messageImgPart.setDisposition(MimeBodyPart.INLINE);
messageImgPart.setFileName("logo inline image");
messageImgPart.attachFile(img_file);
multipart.addBodyPart(messageImgPart);
return MimeMultipart;
}
此方法将MimeMultipart编码为HexString: (它还附加带边界的内容类型。)
public String encode(MimeMultipart body) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
body.writeTo(baos);
String hex_body = Hex.encodeHexString(baos.toByteArray());
hex_body += ";" + body.getContentType();
return hex_body;
}
最后一个方法必须解码字符串:
public MimeMultipart decode(String encoded_body) throws Exceptions {
MimeMultipart body = null;
String[] parts = encoded_body.split(";", 2);
byte[] body_b = Hex.decodeHex(parts[0].toCharArray());
ByteArrayDataSource bads = new ByteArrayDataSource(body_b, parts[1]);
body = new MimeMultipart(bads);
return body;
}
我做了一些检查:
1)我发送了原始的MimeMultipart:
MimeMessage msg = new MimeMessage(session);
msg.setHeader("Content-Type", "text/html; charset=\"UTF-8\"");
msg.setSubject(subject, "UTF-8");
msg.setContent(body, "text/html; charset=\"UTF-8\"");
Transport.send(msg);
我根据需要收到邮件(html显示为html,图像显示为图像) 当我以相同的方式发送编码&gt;解码的邮件时,我得到源html而不是渲染一个,并且图像似乎已损坏 2)我检查了解码的MimeMultipart并看到了0个部分。
这里可能有什么问题?
更新: 大约2:MimeMultipart包含0个部分,因为从流中解析仅在需要时完成,即在getParts()调用期间。