I'm using Apache Commons Email 1.1 and I can't figure out how to attach a file to an HtmlEmail. If I run the code below, I get an email with an attachment, but the HTML message comes across as an attachment also.
If I don't call email.attach() the HTML message come through as you would expect, but I need both the HTML message to come through and the attachment. What am I missing?
HtmlEmail email = new HtmlEmail();
email.setHostName("localhost");
email.addTo("[email protected]", "Test");
email.setFrom("[email protected]", "Test App");
email.setSubject("Test message");
email.setHtmlMsg("<div style='font-size: 20px; color: green;'>This is html email</div>");
EmailAttachment attachment = new EmailAttachment();
attachment.setPath(pdfPath);
attachment.setDisposition(EmailAttachment.ATTACHMENT);
email.attach(attachment);
email.send();
email.attach(new ByteArrayDataSource(pdfBytes, "application/pdf"),
"document.pdf", "Document description",
EmailAttachment.ATTACHMENT);
this works with commons-email 1.1.
pdfBytes
should be a byte[]
containing the bytes of the pdf document. If that doesn't suit you, you can try other DataSource
implementations, but I can't guarantee they'd work (although they should).
(The one above is org.apache.commons.mail.ByteArrayDataSource
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With