Apache Commons Email encode 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 编码的?

最简单的解决方案是执行以下操作:

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

希望对您有所帮助。

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

最新更新