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

8

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 user. It was working while you were using your own mail server.

Recently I started using a Gmail account to send the emails. From there, the function does not generate any more 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
}   

E-mail class

@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 the error in gmail.

  

Mail Delivery Subsystem

     

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

     

The response from the remote server was: 550 5.1.1   : Recipient address   Rejected: Unknown user in virtual mailbox table

     

Final-Recipient: 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 transportealvorada.com.br.) Diagnostic-Code: smtp; 550 5.1.1   : Recipient address   rejected: User unknown in virtual mailbox Last-Attempt-Date:   Wed, 08 Mar 2017 05:53:40 -0800 (PST)

    
asked by anonymous 08.03.2017 / 15:12

2 answers

2

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

  

A simple thing you can do that does not completely resolve but can   to minimize people typing the wrong email is to type in two   times and make an error if both fields are not the same, as well as checking with regular expression about the validity of the email.

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

There was no error because the email was sent correctly . Only to an address that does not exist.

When your email arrived on the server of the domain transportealvorada.com.br that server looked at the table of emails and saw that this email did not exist and sent the response to gmail saying that it did not exist. The reply was pro gmail because the email sent out 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 who sent it only became aware that the address was wrong after the letter returned.

If just making the person check if they are typing right is not enough, you can try to look for some service to validate emails before sending them. Here's a service: link

Testing on the site link I saw that email [email protected] did not exist, but [email protected] exists.

This site sends an email and starts a conversation between servers to see 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 topics: SMTP Commands:

link

Related pages of people trying to validate the existence of an email with Java with some success:

link

link

    
17.03.2017 / 05:41
1

I fear the only way to resolve this problem is to periodically access Gmail emails and look for the return message.

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

    
16.03.2017 / 20:51