sending email in java does not show the error when it cannot send the same

I created a system where the user himself registers and the password is sent by email. If you can not send the email, it generates an error and does not create the user, notifying the same. It was working while I was using my own email server.

I recently switched to using a Gmail account to send the emails. From there the function no longer generates error when Gmail can not deliver the message. With this the user does not know that a problem has occurred and does not receive the password.

import java.io.Serializable;

import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

// ... Demais imports

@ViewScoped
public class Mailer implements Serializable{

    private static final long serialVersionUID = 1L;

    @Inject
    private PropriedadesEmail propriedadesEmail;

    private String mailTo; 
    private String mailCC;
    private String mailSubject;
    private String mailBody;


    public void sendMail() throws NegocioException {

        try{    
            MimeMessage generateMailMessage = propriedadesEmail.mineMessage(); // new MimeMessage(getMailSession);

            generateMailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(this.mailTo));
            if(this.mailCC != null)
                generateMailMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(this.mailCC));

            generateMailMessage.setSubject(this.mailSubject);
            generateMailMessage.setFrom(propriedadesEmail.getMailUsername());

            generateMailMessage.setContent(this.mailBody, "text/html");

            Transport transport = propriedadesEmail.getMailSession().getTransport("smtp");

            transport.connect( propriedadesEmail.getMailServerHost()  
                                  ,propriedadesEmail.getMailUsername()  
                                  ,propriedadesEmail.getMailPassword() 
                                 );

            transport.sendMessage(generateMailMessage, generateMailMessage.getAllRecipients());
            transport.close();

        } catch (AddressException e) {
            System.out.println("-------- ERRO AddressException e "+e.getMessage());
            e.printStackTrace();
            throw new NegocioException(TrataErro.buscaErroEmail(e, "Problemas ao enviar email"));
        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println("-------- ERRO MessagingException e "+e.getMessage());
            throw new NegocioException(TrataErro.buscaErroEmail(e, "Problemas ao enviar email"));       
        } catch (Exception e) {
            e.printStackTrace();
            throw new NegocioException(TrataErro.buscaErroEmail(e, "Problemas ao enviar email"));
        }

    }

    // ... Demais metodos e clases
}   

Properties Classemail

@ApplicationScoped
public class PropriedadesEmail implements Serializable{

    private static final long serialVersionUID = 1L;

    private String  mailServerHost; 
    private String  mailServerPort;
    private String  mailEnableSsl;
    private String  mailEnableStarttls;
    private String  mailAuth;
    private String  mailUsername;
    private String  mailPassword;
    private Session mailSession;

    @PostConstruct
    private void init(){
        Properties props = new Properties();
        try {
            props.load(ManipulacaoProperties.buscaFile(ManipulacaoProperties.CONFIG_EMAIL));
            mailServerHost      = props.getProperty("mail.server.host");  
            mailServerPort      = props.getProperty("mail.server.port");
            mailEnableSsl       = props.getProperty("mail.enable.ssl");
            mailEnableStarttls  = props.getProperty("mail.enable.starttls");
            mailAuth            = props.getProperty("mail.auth");
            mailUsername        = props.getProperty("mail.username");
            mailPassword        = props.getProperty("mail.password");

            mailSession             = Session.getDefaultInstance(mailServerProperties(), null);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new NegocioException("Problemas ao abrir o arquivo de configuração. Contate o administrador"); 
        }
    }

    public MimeMessage mineMessage() {
        return new MimeMessage(this.getMailSession());
    }


    private Properties mailServerProperties() {
        Properties props = new Properties();
        try {
            props.load(ManipulacaoProperties.buscaFile(ManipulacaoProperties.CONFIG_EMAIL));

            Properties mailServerProperties = System.getProperties();
            mailServerProperties.put("mail.smtp.port", this.getMailServerPort());
            mailServerProperties.put("mail.smtp.auth", this.getMailAuth());
            mailServerProperties.put("mail.smtp.starttls.enable", this.getMailEnableStarttls());


            return mailServerProperties;

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new NegocioException("Problemas ao abrir o arquivo de configuração. Contate o administrador"); 
        }
    }

Mail.properties

mail.server.host=smtp.gmail.com
mail.server.port=587
mail.enable.ssl=false
mail.enable.starttls=true
mail.auth=true
[email protected]
mail.password=*******************

Email returned with error in gmail.

Mail Delivery Subsystem

Address Not Found message was not delivered to [email protected] because the address was not found. Check for typos or spaces and try again.

The remote server response was: 550 5.1.1 : Recipient address rejected: User unknown in virtual mailbox table

End-container: rfc822; [email protected] Action: failed Status: 5.1.1 Remote-MTA: dns; mail2.transportesalvorada.com.br. (201.148.108.74, the server for the domain transportesalvorada.com.br.) Diagnostic-Code: smtp; 550 5.1.1 : Recipient address rejected: User unknown in virtual mailbox table Last-Attempt-Date: Wed, 08 Mar 2017 05:53:40 -0800 (PST)

Author: Velasco, 2017-03-08

2 answers

The problem in question is the email being typed wrong. (Not that the email is invalid, it is simply a valid email that does not exist)

A simple thing you can do that doesn't solve it completely but can minimizing people typing wrong email is putting two times and give error if the two fields are not the same, in addition to checking with regular expression about the validity of the email.

According to the email that Gmail sent you, the email [email protected] does not exist.

Gave no error because the email was sent correctly . Except for an address that doesn't exist.

When your email arrived on the domain server transportesalvorada.com.br this server looked at the table of emails and saw that this email did not exist and sent the reply pro gmail saying that the same did not exist. The answer was pro gmail because the email sent came out of the server there.

if the postman takes a letter to a residence where the address is wrong it returns to the sender. Notice that the letter was sent and whoever sent it only became aware that the address was wrong after the letter came back.

If just making the person check if they are typing right is not enough, you can try looking for some service to validate emails before sending them. A service follows: http://www.verifyemailaddress.org/email-verification-api.html

Testing on the site http://www.verifyemailaddress.org / I saw that the email [email protected] did not exist, but [email protected] does exist.

This site sends an email and starts a conversation between servers to check if the email exists.

MX record found: mail2.transportesalvorada.com.br (Priority 5)
MX record found: mail3.transportesalvorada.com.br (Priority 5)
Connecting to mail2.transportesalvorada.com.br
Connected to mail2.transportesalvorada.com.br
Dialog with mail2.transportesalvorada.com.br ok
------------------------------------------------------------
220 mail3.transportesalvorada.com.br running OSTec Mail Server 3000
HELO verifyemailaddress.org
250 mail3.transportesalvorada.com.br
MAIL FROM: <[email protected]>
250 2.1.0 Ok
RCPT TO: <[email protected]>
250 2.1.5 Ok
QUIT
221 2.0.0 Bye
------------------------------------------------------------
Email address [email protected] accepted

Related subjects: SMTP commands:

Http://www.samlogic.net/articles/smtp-commands-reference.htm

Related pages of people who tried to do this validation of existence of an email with Java with some success:

Https://stackoverflow.com/questions/13514005/how-to-check-mail-address-is-exists-or-not

Http://www.rgagnon.com/javadetails/java-0452.html

 3
Author: Antonio Alexandre, 2017-05-23 12:37:28

I'm afraid the only way to solve this problem is to periodically access Gmail emails and search for the return message.

Email is a protocol that was more or less stabilized in the 1970s, and is not a real-time protocol. MTA (Mail Transport Agent), like Gmail, have the freedom to hold email indefinitely and make multiple delivery attempts before giving up. They can even make an indirect delivery, sending to another email server, and that other one being the one in charge of delivering to the final recipient (though I doubt any system works that way these days). If it worked with your own email server, it is because it made an attempt to deliver immediately, and already returned the error in case of failure. Gmail is not like that, and the warning of their failure is done by email.

 1
Author: lvella, 2017-03-16 19:51:15