How to add inline images and attach files to Java mail

I am using the Java mail API to send email. I have to send an email containing both the embedded images indicated by the HTML <img> tag and some attached files.

What type of content should I use for MimeMultipart , which contains parts for embedded images and attachment files?

 MimeMultipart multipartInline = new MimeMultipart(?); 
+4
source share
2 answers

Here are three different types of multi-page content:

  • multipart / mixed - usually used to contain the main body of the message with "attachment"
  • multipart / alternative - used to send the same data in various formats, for example, plain text and html
  • multipart / related - commonly used to contain html body part and image links in that html

You can embed these different types in all sorts of interesting ways.

To answer the original question, you want to receive a message with this structure:

 main message multipart/mixed multipart/related text/html - main html content image/jpg - an image referenced by the html application/pdf - or whatever, for the first attachment 

The html part will want to link to the part of the image using the URL link "cid:", and the part of the image will need the corresponding Content-ID header. RFC2387 contains more detailed information. You can probably find some examples by searching the JavaMail forum .

+5
source

You must use one or two headers for each attachment:

If this is a normal attachment:

  • Content-Disposition: attachment; file name = ...

If it is an embedded application (image for your mail)

  • Content-Disposition: inline
  • Content-ID: arbitrary-id

This is an extract for a small sending program that I programmed a while ago:

bodyPart is a MimeBodyPart .

 bodyPart.setHeader("Content-Disposition", disp + "; filename=" + encodedFileName); bodyPart.setHeader("Content-Transfer-Encoding", "base64"); if (att.getContextId() != null && att.getContextId().length() > 0) bodyPart.setHeader("Content-ID", "<" + att.getContextId() + ">"); 

In it: disp has inline or attachment , and att.getContextId() has some arbitrary identifier for the attached attachment.

My recipe for HTML mail

 message has via .setContent(...) mainMultipart is a MimeMultiPart("alternative") and has via .addBodyPart(...) textBodyPart is a MimeBodyPart with content-type "text/plain" relatedMultipart is a MimeMultipart("related") and has via .addBodyPart(...) htmlBodyPart "text/html; charset=utf-8" INLINED-ATTACH1 INLINED-ATTACH2 NORMAL-ATTACH1 NORMAL-ATTACH2 
0
source

Source: https://habr.com/ru/post/1381133/


All Articles