title: Alert about bounced emails using Spring Boot
body: <p>I have a Spring Boot application that sends emails. For any action that requires notification, a <code>Mail</code> instance is created with status <code>PENDING</code> in the database and a job is run to send the pending emails every minute. The status of the <code>Mail</code> instances are set as <code>PENDING</code>, <code>SENT</code> or <code>FAILED</code>. </p>
  
  <pre><code>try {
      Properties props = new Properties();
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.starttls.enable", "true");
      props.put("mail.smtp.host", host);
      props.put("mail.smtp.port", port);
      props.put("mail.smtp.from", myEmailAddress);
      props.put("mail.smtp.timeout", 2000);
  
      Session session = Session.getInstance(props, new javax.mail.Authenticator() {
          protected PasswordAuthentication getPasswordAuthentication() {
              return new PasswordAuthentication(username, password);
          }
      });
  
      MimeMessage message = new MimeMessage(session);
      MimeMultipart content = getContent(mail, message, username);
      message.setContent(content);
      Transport.send(message);
      mail.setStatus(MailStatus.SENT);
      mailService.save(mail);
  } catch (MailConnectException mce) {
      mail.setStatus(MailStatus.FAILED);
      mailService.save(mail);
  } catch (Exception e) {
      // other actions
  }
  </code></pre>
  
  <p>Now, this works fine if a valid email id is provided. But when the receiving email address is a non-existent one like <code>somerandomname@gmail.com</code>, there are no exceptions thrown. From what I read from similar questions in SO and elsewhere, I understand that mail sending is an asynchronous process and hence there is no way to determine that a given email is existing or not (or other issues like Inbox full). That is why after the <code>Transport.send(message);</code> statement, the <code>mail.setStatus(MailStatus.SENT);</code> statement will always be executed irrespective of the email address being present. Later the mail will actually be attempted to be sent and I get an email in <code>myEmailAddress</code> with content like the following:</p>
  
  <blockquote>
    <p>The response from the remote server was: 550 5.1.1
    somerandomname@gmail.com User unknown</p>
  </blockquote>
  
  <p>Okay, accepted until this point. But now I need a way to alert the user that the email couldn't be sent because they entered an invalid email so that they can update their email. More specifically, I need to set the status of the <code>Mail</code> instance to <code>FAILED</code>. What is the best way to achieve this?</p>