Abhishek Kumar Jain
Abhishek Kumar Jain

Reputation: 17

Email response in java

I am working in email response but unable to find any solution.I need to get response when email failure or success in Java. Code-->

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    Session session = Session.getInstance(props,
      new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
      });

    try { 
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("[email protected]"));
        message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse("[email protected]"));
        message.setSubject("Testing Subject");
        message.setText("Dear Mail Crawler,"
            + "\n\n No spam to my email, please!");

        Transport.send(message);

Upvotes: 1

Views: 1564

Answers (2)

MaVRoSCy
MaVRoSCy

Reputation: 17849

If an Exception is raised you can catch it in your exception hanlding:

try{
....
  Transport.send(message);
....

}catch(Exception ex){
  //You can catch exception here and deal with it
}

Some popular exception types include:

  • javax.mail.SendFailedException: Invalid Addresses; nested exception is: javax.mail.SendFailedException: 501 : recipient address must contain a domain
  • Could not connect to SMTP host: yourdomain.com, port: 25; nested exception is: java.net.ConnectException: connection to yourdomain.com timed out
  • Could not connect to SMTP host: yourdomain.com, port: 25; nested exception is: java.net.ConnectException: Connection refused: connect

Upvotes: 0

npinti
npinti

Reputation: 52185

Emails are fire and forget, meaning that once you send it, there is no way to get an exception out of it should it fail or some return code/value should it succeed.

As far as I know:

  • To check if an email has failed, keep checking your inbox to see if you get any delivery failure notifications
  • To check if an email has been delivered and read, you could attach an image which is delivered by a link on a server you have access to. The URL of the image would be something of the sort: <img src="..../image/someuniqueid".... You could then assign image id's to recipients. When they open the email, your server will be hit together with the unique ID you have provided in your email. This will let you know when was an email opened and by which recipient.

Upvotes: 1

Related Questions