In this article, we will use a similar technique plus some modification in order to embed some images directly into the message. The embedded images are called inline attachments which users see the images right inside the e-mail’s content. That’s different with regular attachments which the users have to download and open them manually.
The message must in HTML format in order to have inline images, so we should set content type of the message as follows:
1
2
| MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setContent(htmlMessage, "text/html" ); |
Where htmlMessage is a String represents content of the message with HTML tags:
1
2
3
| String htmlMessage = "<html>Hi there,<br>" ; htmlMessage += "See this cool pic: <img src=\"cid:AbcXyz123\" />" ; htmlMessage += "</html>" ; |
As you notice in the HTML code above, we use the <img> tag to include an image, but its src attribute does not point to name of the image. Instead, the src attribute must refer to Content-ID header’s value of a MIME part which contains the actual image, in the following form:
src=”cid:<content_id>”
Then the image part should be created as follows:
1
2
3
4
5
| MimeBodyPart imagePart = new MimeBodyPart(); imagePart.setHeader( "Content-ID" , "AbcXyz123" ); imagePart.setDisposition(MimeBodyPart.INLINE); // attach the image file imagePart.attachFile(imageFilePath); |
Value of the Content-ID header must be a unique identifier. This convention is described in the RFC 2387.
Read full article from Embedding images into e-mail with JavaMail
No comments:
Post a Comment