Request a Delivery / Read Receipt in Javamail

The read receipt (i.e. “Disposition-Notification-To” SMTP header) is a request for the receiving email client to send a DSN (delivery status notification) as soon as the recipient opens the email.

The request for the receipt is sent as a header attached to the mail using the method MimeMessage.setHeader().

Keep in mind that a receipt request may not be always honored because
1) A mail client may not recognize the special Disposition-Notification-To header.
2) The end user may have that functionality turned off or not choose to send one for your particular email.

It’s possible to ask for a delivery receipt too (i.e. “Return-Receipt-To” SMTP header). This kind of receipt is sent as soon as the mail server receives the mail. This one is rarely enabled on a mail server and its recommended usage is for debugging purposes only.

import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

class SimpleMail {
    public static void main(String[] args) throws Exception{
      Properties props = new Properties();
      props.setProperty("mail.transport.protocol", "smtp");
      props.setProperty("mail.host", "mydomain.com");
      props.setProperty("mail.user", "user");     // using the mail account
      props.setProperty("mail.password", "pwd");  //     user@mydomain.com

      Session mailSession = Session.getInstance(props, null);
      Transport transport = mailSession.getTransport();

      MimeMessage message = new MimeMessage(mailSession);

      message.setHeader("Disposition-Notification-To", "user@mydomain.com");
      //  message.setHeader("Return-Receipt-To", "user@mydomain.com");

      message.setSubject("Testing javamail plain");
      message.setContent("I'm alive", "text/plain");
      message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress("maixuanviet.com@gmail.com"));

      transport.connect
         ("mail.mydomain.com", 587, "user", "pwd");
      //   mail server       port    user    pwd
      transport.sendMessage(message,
          message.getRecipients(Message.RecipientType.TO));
      transport.close();

      System.out.println("Done.");
    }
}

Done! Happy Coding!