Apache Commons Email with attach with base64

我正在尝试通过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编码?

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

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

 // 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。

希望能帮助到你。