JAVA  —  Sending HTML Email With Images In Localhost

Persiapan

1. Menginstal jar atau dependency (apabila menggunakan java maven project) yang diperlukan

Jika Anda ingin mengirim email menggunakan Aplikasi Java, caranya cukup sederhana, akan tetapi untuk memulainya Anda harus terlebih dahulu menginstal JavaMail API dan Java Activation Framework (JAF) di mesin Anda.

Anda dapat mengunduh JavaMail versi terbaru di sini https://javaee.github.io/javamail/

Anda dapat mengunduh JAF versi terbaru di sini https://jar-download.com/?search_box=javax.activation

Unduh dan unzip file-file ini, di direktori tingkat atas yang baru saja dibuat dan Anda akan menemukan sejumlah file jar untuk kedua aplikasi tersebut. Anda perlu menambahkan file javax.mail.jar dan activation.jar di CLASSPATH Anda.

2. Instalasi FakeSMTP sebagai server untuk test email di lokal Anda

Untuk referensi instalasi bisa Anda lihat pada tautan berikut:

Source Code Sending HTML Email with Images In LocalHost

package mail;

/* * Tambahkan jar berikut ke dalam classpath. 
 javax.mail-1.6.2.jar dan activation-1.1.1.jar
 * */

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class SendHtmlEmailV4 {

 public static void main(String[] args) {
  // Assuming you are sending email from through fake smtp
  String smtpHost = "localhost";
  int smtpPort = 25;
  // String smtpAuth = "false";
  final String smtpUser = "";
  final String smtpPass = "";

  // Set Address
  String to = "dimasogan231@gmail.com";
  String from = "ognivid@gmail.com";
  String cc = "";
  String bcc = "";
  String subject = "test kirim email html beserta gambar";

  // Set HTML
   String htmlText = "<html><header> <img src=\"cid:image\" alt=\"Logo\" width=\"default\" height=\"50\"> </header><body><br>Dear My Fans ,<br><br>follow and subscribe my medium page<br><br> Regards, <br><br> Dimas Agung Prakasa</body></html>";

  // second part (the image)
  DataSource fds = new FileDataSource("C:\\Users\\dimas.prakasa\\Downloads\\logo.png");

  // Get system properties
  Properties properties = System.getProperties();

  // Setup mail server
  properties.put("mail.smtp.host", smtpHost);
  properties.put("mail.smtp.port", smtpPort);
  // properties.put("mail.smtp.auth", smtpAuth);

  // Creates a new session with an authenticator
  Authenticator auth = new Authenticator() {
   public PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(smtpUser, smtpPass);
   }
  };

  // Get the Session object.// and pass username and password
  Session session = Session.getInstance(properties, auth);

  // Used to debug SMTP issues
  session.setDebug(true);

  try {
   // Create a default MimeMessage object.
   MimeMessage message = new MimeMessage(session);

   // Set From: header field of the header.
   message.setFrom(new InternetAddress(from));

   // Set to: single recipient or multiple recipients
   String[] toRecipientList = to.split(";");
   InternetAddress[] toRecipientAddress = new InternetAddress[toRecipientList.length];
   int toCounter = 0;
   for (String recipient : toRecipientList) {
    toRecipientAddress[toCounter] = new InternetAddress(recipient.trim());
    toCounter++;
   }
   message.addRecipients(Message.RecipientType.TO, toRecipientAddress);

   // Set cc: single recipient or multiple recipients
   if (!cc.isEmpty()) {
    String[] ccRecipientList = cc.split(";");
    InternetAddress[] ccRecipientAddress = new InternetAddress[ccRecipientList.length];
    int ccCounter = 0;
    for (String recipient : ccRecipientList) {
     ccRecipientAddress[ccCounter] = new InternetAddress(recipient.trim());
     ccCounter++;
    }
    message.addRecipients(Message.RecipientType.CC, ccRecipientAddress);
   }

   // Set bcc: single recipient or multiple recipients
   if (!bcc.isEmpty()) {
    String[] bccRecipientList = bcc.split(";");
    InternetAddress[] bccRecipientAddress = new InternetAddress[bccRecipientList.length];
    int bccCounter = 0;
    for (String recipient : bccRecipientList) {
     bccRecipientAddress[bccCounter] = new InternetAddress(recipient.trim());
     bccCounter++;
    }
    message.addRecipients(Message.RecipientType.BCC, bccRecipientAddress);
   }

   // Set Subject: header field
   message.setSubject(subject);

   // This mail has 2 part, the BODY and the embedded image
   MimeMultipart multipart = new MimeMultipart("related");

   // prosesbodyhtml
   BodyPart messageBodyPart = new MimeBodyPart();
   messageBodyPart.setContent(htmlText, "text/html");
   // add it
   multipart.addBodyPart(messageBodyPart);

   // prosesbodyimage
   messageBodyPart = new MimeBodyPart();
   messageBodyPart.setDataHandler(new DataHandler(fds));
   messageBodyPart.setHeader("Content-ID", "<image>");
   // add image to the multipart
   multipart.addBodyPart(messageBodyPart);

   // Send the actual HTML message.
   message.setContent(multipart);

   System.out.println("sending...");
   // Send message
   Transport.send(message);
   System.out.println("Sent message successfully....");
  } catch (MessagingException mex) {
   mex.printStackTrace();
  }

 }
}

Kemudian compile dan jalankan program.

Output

$ java SendHTMLEmail
Sent message successfully....

Jika dibuka melalui Outlook, maka akan didapatkan tampilan seperti berikut ini:

Referensi:
https://www.tutorialspoint.com/java/java_sending_email.htm