Inline images in email using JavaMail
I want to send an email with an inline image using javamail.
I'm doing something like this.
MimeMultipart content = new MimeMultipart("related");
BodyPart bodyPart = new MimeBodyPart();
bodyPart.setContent(message, "text/html; charset=ISO-8859-1");
content.addBodyPart(bodyPart);
bodyPart = new MimeBodyPart();
DataSource ds = new ByteArrayDataSource(image, "image/jpeg");
bodyPart.setDataHandler(new DataHandler(ds));
bodyPart.setHeader("Content-Type", "image/jpeg; name=image.jpg");
bodyPart.setHeader("Content-ID", "<image>");
bodyPart.setHeader("Content-Disposition", "inline");
content.addBodyPart(bodyPart);
msg.setContent(content);
I've also tried
bodyPart.setHeader("inline; filename=image.jpg");
and
bodyPart.setDisposition("inline");
but no matter what, the image is being sent as an attachment and the Content-Dispostion is turning into "attachment".
How do I send an image inline in the email using javamail?
Solution 1:
Your problem
As far as I can see, it looks like the way you create the message and everything is mostly right! You use the right MIME types and everything.
I am not sure why you use a DataSource and DataHandler, and have a ContentID on the image, but you need to complete your question for me to be able to troubleshoot more. Especially, the following line:
bodyPart.setContent(message, "text/html; charset=ISO-8859-1");
What is in message
? Does it contains <img src="cid:image" />
?
Did you try to generate the ContentID with String cid = ContentIdGenerator.getContentId();
instead of using image
Source
This blog article taught me how to use the right message type, attach my image and refer to the attachment from the HTML body: How to Send Email with Embedded Images Using Java
Details
Message
You have to create your content using the MimeMultipart
class. It is important to use the string "related"
as a parameter to the constructor, to tell JavaMail that your parts are "working together".
MimeMultipart content = new MimeMultipart("related");
Content identifier
You need to generate a ContentID, it is a string used to identify the image you attached to your email and refer to it from the email body.
String cid = ContentIdGenerator.getContentId();
Note: This ContentIdGenerator
class is hypothetical. You could create one or inline the creation of content IDs. In my case, I use a simple method:
import java.util.UUID;
// ...
String generateContentId(String prefix) {
return String.format("%s-%s", prefix, UUID.randomUUID());
}
HTML body
The HTML code is one part of the MimeMultipart
content. Use the MimeBodyPart
class for that. Don't forget to specify the encoding
and "html"
when you set the text of that part!
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setText(""
+ "<html>"
+ " <body>"
+ " <p>Here is my image:</p>"
+ " <img src=\"cid:" + cid + "\" />"
+ " </body>"
+ "</html>"
,"US-ASCII", "html");
content.addBodyPart(htmlPart);
Note that as a source of the image, we use cid:
and the generated ContentID.
Image attachment
We can create another MimeBodyPart
for the attachment of the image.
MimeBodyPart imagePart = new MimeBodyPart();
imagePart.attachFile("resources/teapot.jpg");
imagePart.setContentID("<" + cid + ">");
imagePart.setDisposition(MimeBodyPart.INLINE);
content.addBodyPart(imagePart);
Note that we use the same ContentID between <
and >
and set it as the image's ContentID. We also set the disposition to INLINE
to signal that this image is meant to be displayed in the email, not as an attachment.
Finish message
That's it! If you create an SMTP message on the right session and use that content, your email will contain an embedded image! For instance:
SMTPMessage m = new SMTPMessage(session);
m.setContent(content);
m.setSubject("Mail with embedded image");
m.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
Transport.send(m)
Let me know if that works for you! ;)
Solution 2:
Why don't you try something like this?
MimeMessage mail = new MimeMessage(mailSession);
mail.setSubject(subject);
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "text/html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(new File("complete path to image.jpg"));
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileAttachment.getName());
messageBodyPart.setDisposition(MimeBodyPart.INLINE);
multipart.addBodyPart(messageBodyPart);
mail.setContent(multipart);
in the message, have a
<img src="image.jpg"/>
tag and you should be ok.
Good Luck
Solution 3:
This worked for me:
MimeMultipart rootContainer = new MimeMultipart();
rootContainer.setSubType("related");
rootContainer.addBodyPart(alternativeMultiPartWithPlainTextAndHtml); // not in focus here
rootContainer.addBodyPart(createInlineImagePart(base64EncodedImageContentByteArray));
...
message.setContent(rootContainer);
message.setHeader("MIME-Version", "1.0");
message.setHeader("Content-Type", rootContainer.getContentType());
...
BodyPart createInlineImagePart(byte[] base64EncodedImageContentByteArray) throws MessagingException {
InternetHeaders headers = new InternetHeaders();
headers.addHeader("Content-Type", "image/jpeg");
headers.addHeader("Content-Transfer-Encoding", "base64");
MimeBodyPart imagePart = new MimeBodyPart(headers, base64EncodedImageContentByteArray);
imagePart.setDisposition(MimeBodyPart.INLINE);
imagePart.setContentID("<image>");
imagePart.setFileName("image.jpg");
return imagePart;
Solution 4:
If you are using Spring use MimeMessageHelper
to send email with inline content (References).
Create JavaMailSender bean or configure this by adding corresponding properties to application.properties file, if you are using Spring Boot.
@Bean
public JavaMailSender getJavaMailSender() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost(host);
mailSender.setPort(port);
mailSender.setUsername(username);
mailSender.setPassword(password);
Properties props = mailSender.getJavaMailProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", authEnable);
props.put("mail.smtp.starttls.enable", starttlsEnable);
//props.put("mail.debug", "true");
mailSender.setJavaMailProperties(props);
return mailSender;
}
Create algorithm to generate unique CONTENT-ID
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Random;
public class ContentIdGenerator {
static int seq = 0;
static String hostname;
public static void getHostname() {
try {
hostname = InetAddress.getLocalHost().getCanonicalHostName();
}
catch (UnknownHostException e) {
// we can't find our hostname? okay, use something no one else is
// likely to use
hostname = new Random(System.currentTimeMillis()).nextInt(100000) + ".localhost";
}
}
/**
* Sequence goes from 0 to 100K, then starts up at 0 again. This is large
* enough,
* and saves
*
* @return
*/
public static synchronized int getSeq() {
return (seq++) % 100000;
}
/**
* One possible way to generate very-likely-unique content IDs.
*
* @return A content id that uses the hostname, the current time, and a
* sequence number
* to avoid collision.
*/
public static String getContentId() {
getHostname();
int c = getSeq();
return c + "." + System.currentTimeMillis() + "@" + hostname;
}
}
Send Email with inlines.
@Autowired
private JavaMailSender javaMailSender;
public void sendEmailWithInlineImage() {
MimeMessage mimeMessage = null;
try {
InternetAddress from = new InternetAddress(from, personal);
mimeMessage = javaMailSender.createMimeMessage();
mimeMessage.setSubject("Test Inline");
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom(from);
helper.setTo("[email protected]");
String contentId = ContentIdGenerator.getContentId();
String htmlText = "Hello,</br> <p>This is test with email inlines.</p><img src=\"cid:" + contentId + "\" />";
helper.setText(htmlText, true);
ClassPathResource classPathResource = new ClassPathResource("static/images/first.png");
helper.addInline(contentId, classPathResource);
javaMailSender.send(mimeMessage);
}
catch (Exception e) {
LOGGER.error(e.getMessage());
}
}
Solution 5:
RFC Specification could be found here(https://www.rfc-editor.org/rfc/rfc2392).
Firstly, email html content needs to format like : "cid:logo.png" when using inline pictures, see:
<td style="width:114px;padding-top: 19px">
<img src="cid:logo.png" />
</td>
Secondly, MimeBodyPart object needs to set property "disposition" as MimeBodyPart.INLINE, as below:
String filename = "logo.png"
BodyPart image = new MimeBodyPart();
image.setDisposition(MimeBodyPart.INLINE);
image.setFileName(filename);
image.setHeader("Content-ID", "<" +filename+">");
Be aware, Content-ID property must prefix and suffix with "<" and ">" perspectively, and the value off filename should be same with the content of src of img tag without prefix "cid:"
Finally the whole code is below:
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("[email protected]");
InternetAddress[] recipients = { "[email protected]"};
msg.setRecipients(Message.RecipientType.TO, recipients);
msg.setSubject("for test");
msg.setSentDate(new Date());
BodyPart content = new MimeBodyPart();
content.setContent(<html><body> <img src="cid:logo.png" /> </body></html>, "text/html; charset=utf-8");
String fileName = "logo.png";
BodyPart image = new MimeBodyPart();
image.setHeader("Content-ID", "<" +fileName+">");
image.setDisposition(MimeBodyPart.INLINE);
image.setFileName(fileName);
InputStream stream = MailService.class.getResourceAsStream(path);
DataSource fds = new ByteArrayDataSource(IOUtils.toByteArray(stream), "image/png");
image.setDataHandler(new DataHandler(fds));
MimeMultipart multipart = new MimeMultipart("related");
multipart.addBodyPart(content);
multipart.addBodyPart(getImage(image1));
msg.setContent(multipart);
msg.saveChanges();
Transport bus = session.getTransport("smtp");
bus.connect("username", "password");
bus.sendMessage(msg, recipients);
bus.close();