Apache Commons Email with attach with base64

时间:2012-04-12 06:17:46

标签: java base64 apache-commons-email

我正在尝试通过apache.commons.mail发送一个base64编码的文件,而我无法通过接缝来获取它应该去的Content-Transfer-Encoding: base64标题。

// Create the email
MultiPartEmail email = new MultiPartEmail();
email.setSmtpPort(587);
email.setDebug(false);
email.setHostName("smtp.gmail.com");
email.setAuthentication("from@gmail.com", "password");
email.setTLS(true);

email.addTo("to@example.com");
email.setFrom("from@example.com");
email.setSubject("subject");

email.attach(new ByteArrayDataSource(
     Base64.encodeBase64(attachFull.getBytes()), "text/plain"), 
     "samplefile.txt", 
     "sample file desc", 
     EmailAttachment.ATTACHMENT
);

这就是接收者的目的。

------=_Part_0_614021571.1334210788719
Content-Type: text/plain; charset=Cp1252; name=texto.txt
Content-Transfer-Encoding: quoted-printable
Content-Disposition: attachment; filename=samplefile.txt
Content-Description: sample file desc

如何指定文件是Base64编码?

2 个答案:

答案 0 :(得分:5)

最简单的解决方案是做这样的事情:

// create a multipart leg for a specific attach
MimeMultipart part = new MimeMultipart();
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler (new DataHandler(new ByteArrayDataSource(attachFull.getBytes(), "text/plain")));
messageBodyPart.removeHeader("Content-Transfer-Encoding");
messageBodyPart.addHeader("Content-Transfer-Encoding", "base64");
part.addBodyPart(messageBodyPart);
email.addPart(part);

javax会自动将您的文件转换为base64。

希望它有所帮助。

答案 1 :(得分:1)

您可以尝试覆盖attach方法并在其中设置Content-Transfer-Encoding标头。默认情况下,框架不会为您设置它或者干净地公开MIME bodyPart。