Send inline image in email using JavaMail API

We are explaining here an example of sending inline image in email using JavaMail API.

Difference between inline and attachment in email.

Inline can be seen directly in the message body while attachment cannot be seen directly in the message body, we have to click it to open and view the attachment.

Steps of sending inline image in email using JavaMail API:

    1. Get a session instance from getDefaultInstance() or getInstance() method of Session class.
    2. Create a message we have to pass session object in MimeMessage class constructor.
    3. Use the InternetAddress class to set the information of sender and recipient.
    4. Create the MimeBodyPart object and set actual message.
    5. Create DataHandler object and set image in it.
    6. Create a new MimeBodyPart object and set DataHandler object in it.
    7. Create a MimeMultipart object and set MimeBodyPart objects in it.
    8. Set the multipart object in the message object.
    9. Use send() method of javax.mail.Transport class to send the message.

import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
* This class is used to send email with image.
* @author javawithease

public class SendEmailWthImage {
final String senderEmailId = "";
final String senderPassword = "****";
final String emailSMTPserver = "";
public SendEmailWthImage (String receiverEmail,
String subject, String messageText, String imagePath) {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("", emailSMTPserver);
try {
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
Message emailMessage = new MimeMessage(session);
emailMessage.setFrom(new InternetAddress(senderEmailId));
MimeBodyPart messageBodyPart1 = new MimeBodyPart();
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
DataSource source = new FileDataSource(imagePath);
messageBodyPart2.setDataHandler(new DataHandler(source));
Multipart multipart = new MimeMultipart();
System.out.println("Email send successfully.");
} catch (Exception e) {
System.err.println("Error in sending email.");
private class SMTPAuthenticator extends
javax.mail.Authenticator {
public PasswordAuthentication
getPasswordAuthentication() {
return new PasswordAuthentication(senderEmailId,
public static void main(String[] args) {
new SendEmailWthImage ("", "Test Email",
"Hi, This is a test email with image.", "F:\\jai.jpg");


Email send successfully.

No comments: