Sample code for 30+ languages & platforms
Java

Embed Image in HTML Email

Demonstrates how to create and send an HTML email with an embedded image.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Email;
import com.chilkatsoft.chilkat2.MailMan;

public class ChilkatExample {

    public static void main(String[] args) {
        // This example requires the Chilkat API to have been previously unlocked.
        // See Global Unlock Sample for sample code.

        // The mailman object is used for sending and receiving email.
        MailMan mailman = new MailMan();

        // Set the SMTP server.
        mailman.setSmtpHost("smtp.comcast.net");

        // Create a new email object
        Email email = new Email();

        // Add an embedded image to the HTML email.
        String fileOnDisk = "images/dude2.gif";
        String filePathInHtml = "dudeAbc.gif";

        // Embed the GIF image in the email.
        try {
            email.addRelatedFile2(fileOnDisk, filePathInHtml);
        } catch (ChilkatException e) {
            System.out.println(mailman.getLastErrorText());
            return;
        }

        // The src attribute for the image tag is set to the filePathInHtml:
        String htmlBody = "<html><body>Embedded Image:<br><img src=\"dudeAbc.gif\"></body></html>";

        // Set the basic email stuff: HTML body, subject, "from", "to";
        email.setHtmlBody(htmlBody);
        email.setSubject("Java HTML email with an embedded image.");
        email.addTo("Admin", "admin@chilkatsoft.com");
        email.setFrom("Chilkat Support <support@chilkatsoft.com>");

        try {
            mailman.sendEmail(email);
            System.out.println("Mail Sent!");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
        }
    }
}