Skip to content

Instantly share code, notes, and snippets.

@bjpeterdelacruz
Last active January 11, 2018 22:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjpeterdelacruz/478195960dcf5f72a9e2084554d15a59 to your computer and use it in GitHub Desktop.
Save bjpeterdelacruz/478195960dcf5f72a9e2084554d15a59 to your computer and use it in GitHub Desktop.
How to send an e-mail message with a PDF attachment and an inline image
private void send(String toAddress, String subject, String text, byte[] attachment) {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost(mailHost);
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper msgHelper = new MimeMessageHelper(message, true);
msgHelper.setSubject(subject);
msgHelper.setFrom(fromAddress);
msgHelper.setTo(toAddress);
Multipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(text, "UTF-8", "html");
multipart.addBodyPart(messageBodyPart);
MimeBodyPart imagePart = new MimeBodyPart();
imagePart.attachFile(new File(PdfMailServiceImpl.class.getClassLoader().getResource("images/Energy_Office-logo.png").toURI()));
imagePart.setContentID("<" + "101" + ">");
imagePart.setDisposition(MimeBodyPart.INLINE);
multipart.addBodyPart(imagePart);
MimeBodyPart pdfPart = new MimeBodyPart();
DataSource pdfSrc = new ByteArrayDataSource(attachment, mime);
pdfPart.setDataHandler(new DataHandler(pdfSrc));
pdfPart.setFileName(formFilename);
multipart.addBodyPart(pdfPart);
message.setContent(multipart, "text/html");
message.saveChanges();
mailSender.send(message);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment