How to know is mail deleverd or not using javax.mail
When using javax.mail
to send emails, you can't directly know if the email has been delivered or not. However, you can use some techniques to determine the status of the email:
- Set a return receipt: You can set a return receipt using the
setReturnReceiptRequested()
method of theMessage
class. This will send a confirmation email to the sender when the recipient opens the email. This way, you can know when the email has been delivered and opened. - Use a delivery status notification (DSN): Some email servers support DSNs, which provide a notification when an email is delivered or bounced. You can set the
setNotifyOptions()
method of theTransport
class to request a DSN. This will send a notification to the sender when the email is delivered or bounced. - Check the email server's response: When sending an email using
javax.mail
, you can check the response from the email server to determine if the email was delivered or not. The response will contain a status code, such as "250" for a successful delivery or "550" for a failed delivery. - Use a third-party service: There are third-party services, such as SendGrid or Mailgun, that provide email tracking and delivery status notifications. You can integrate these services with your
javax.mail
code to track the delivery status of your emails.
Here's an example of how you can use javax.mail
to set a return receipt and request a DSN:
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
// Create a session
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "password");
}
});
// Create a message
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
message.setSubject("Test email");
message.setText("This is a test email");
// Set a return receipt
message.setReturnReceiptRequested(true);
// Request a DSN
Transport transport = session.getTransport();
transport.setNotifyOptions(Transport.NOFOLLOWUP);
// Send the email
transport.sendMessage(message, message.getAllRecipients());
In this example, we set the return receipt requested and request a DSN using the setNotifyOptions()
method. When the email is delivered or bounced, the email server will send a notification to the sender with the delivery status.