简体   繁体   中英

How to add inline images and attach files in Java mail

I am using the Java mail API for e-mailing. I have to e-mail a message that contains both inline images specified by HTML's <img> tag and some attached files.

What content type I should use for MimeMultipart that contains the parts for inline images and attachment files?

MimeMultipart multipartInline = new MimeMultipart(?);

There's three different types of multipart content to consider here:

  • multipart/mixed - commonly used to contain the main message body with "attachments"
  • multipart/alternative - used to send the same data in different formats, eg, plain text and html
  • multipart/related - commonly used to contain an html body part and the images referenced by that html

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

To answer the original question, you want 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 reference the image part using a "cid:" URL reference, and the image part will need a corresponding Content-ID header. RFC2387 has more details. You can probably find some examples by searching the JavaMail forum .

You must use one or two headers for each attach:

If it's a normal attach:

  • Content-Disposition: attachment; filename=...

If it's an inline attach (image for your mail)

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

This is extracted for a small sending program I've programmed some time 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 ID for the inlined attach.

My recipe for an 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM