HTML with Embedded Image and Plain Text Email

April 9, 2010

This code shows an example of sending an email that has a plain text version, and an embedded graphic in the HTML version.

try
{
  Properties lProperties = System.getProperties();
  lProperties.put("mail.smtp.host", lSmtpServer);

  Session lSession = Session.getDefaultInstance(lProperties, null);
  MimeMessage lEmailMessage = new MimeMessage(lSession);

  if ((lToUser.getEmail().length() > 0) && (lFromUser.getEmail().length() > 0))
  {
    lEmailMessage.setFrom(new InternetAddress(lFromUser.getEmail()));
    lEmailMessage.setSubject("Email Subject");
    lEmailMessage.setRecipients(MimeMessage.RecipientType.TO, InternetAddress.parse(lToUser.getEmail(), false));
    lEmailMessage.setSentDate(new Date());

    // Setup container
    MimeMultipart lMultipartRoot = new MimeMultipart("related");
    MimeBodyPart lContentRoot = new MimeBodyPart();
    MimeMultipart lMultipartAlternate = new MimeMultipart("alternative");

    // Plain text part
    BodyPart lPlainBodyPart = new MimeBodyPart();
    lPlainBodyPart.setContent(lMessage.getMessageString(), "text/plain");
    lMultipartAlternate.addBodyPart(lPlainBodyPart);

    // HTML part
    BodyPart lMessageBodyPart = new MimeBodyPart();
    String lMessageTextHtml = StringUtils.replace(lMessage.getMessageString(), "\n", "<br>");
    String lMessageText = "<p>" + lMessageTextHtml + "</p><br/><img src='cid:image'>";
    lMessageBodyPart.setContent(lMessageText, "text/html");
    lMultipartAlternate.addBodyPart(lMessageBodyPart);

    // Pull together alternate content
    lContentRoot.setContent(lMultipartAlternate);
    lMultipartRoot.addBodyPart(lContentRoot);

    // Image part          
    BodyPart lImageBodyPart = new MimeBodyPart();
    DataSource lChartDataSource = new FileDataSource(lJpgImageFilePath);
    lImageBodyPart.setDataHandler(new DataHandler(lChartDataSource));
    lImageBodyPart.setHeader("Content-ID", "<image>");
    lMultipartRoot.addBodyPart(lImageBodyPart);

    lEmailMessage.setContent(lMultipartRoot);
    Transport.send(lEmailMessage);
  }
}
catch (Exception lException)
{
  throw new RuntimeException(lException.getMessage(), lException);
}

CSV Attachment

I needed to build on this example to attach a CSV file that I already had in memory as a string. Here's the code to ad another MimeBodyPart which contains a CSV file, and is called app.csv:

MimeBodyPart lAttachment = new MimeBodyPart();
lAttachment.setFileName("app.csv");
lAttachment.setContent(lEmailAttachment, "text/csv");
lMultipartRoot.addBodyPart(lAttachment);

Tags: javamail email html csv