Problems sending email with Javamail

Asked

Viewed 435 times

0

I am developing a Java Web application with Primefaces in which I use javaMail to email with user information, but it is giving error.

The Bean:

@Named
@RequestScoped
public class EnvioEmailBean implements Serializable {

    private static final long serialVersionUID = 1L;

    @Inject
    private Mailer mailer;

    @Inject
    @EnvioEdicao
    private Usuario usuario;

    public void enviarEmail(){
        MailMessage message = mailer.novaMensagem();

        message.to(this.usuario.getEmail())
        .subject("Informações de acesso ao sistema")
        .bodyHtml("<strong>Login:</strong> "+ this.usuario.getEmail() + 
                " com sua senha: ").send();

        FacesUtil.addInfoMessage("E-mail enviado com sucesso!");
    }

}

O Mailconfiguration

public class MailConfigProducer {

    @Produces
    @ApplicationScoped
    public SessionConfig getMailConfig() throws IOException {
        Properties props = new Properties();

        props.load(getClass().getResourceAsStream("/mail.properties"));

        SimpleMailConfig config = new SimpleMailConfig();
        config.setServerHost(props.getProperty("mail.server.host"));
        config.setServerPort(Integer.parseInt(props.getProperty("mail.server.port")));
        config.setEnableSsl(Boolean.parseBoolean(props.getProperty("mail.enable.ssl")));
        config.setAuth(Boolean.parseBoolean(props.getProperty("mail.auth")));
        config.setUsername(props.getProperty("mail.username"));
        config.setPassword(props.getProperty("mail.password"));

        return config;
    }

}

And finally...

mail.server.host=smtp.gmail.com

mail.server.port=465

mail.enable.ssl=true

mail.auth=true

mail.username=******@gmail.com

mail.password=********

The error that appears is.

Caused by: javax.faces.FacesException: #{envioEmailBean.enviarEmail}: com.outjected.email.api.SendFailedException: Send Failed
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:117)
    at org.primefaces.application.DialogActionListener.processAction(DialogActionListener.java:45)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:786)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1251)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    ... 53 more

Caused by: javax.faces.el.EvaluationException: com.outjected.email.api.SendFailedException: Send Failed
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:101)
    ... 58 more

Caused by: com.outjected.email.api.SendFailedException: Send Failed
    at com.outjected.email.impl.MailMessageImpl.send(MailMessageImpl.java:398)
    at com.outjected.email.impl.MailMessageImpl.send(MailMessageImpl.java:405)
    at com.outjected.email.impl.MailMessageImpl.send(MailMessageImpl.java:409)
    at com.outjected.email.impl.MailMessageImpl.send(MailMessageImpl.java:420)
    at com.odontoclinicas.clinicas.controller.EnvioEmailBean.enviarEmail(EnvioEmailBean.java:33)
    at com.odontoclinicas.clinicas.controller.EnvioEmailBean$Proxy$_$$_WeldClientProxy.enviarEmail(EnvioEmailBean$Proxy$_$$_WeldClientProxy.java)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:247)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:267)
    at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:39)
    at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    ... 59 more

Caused by: com.outjected.email.api.SendFailedException: Send Failed
    at com.outjected.email.impl.util.MailUtility.send(MailUtility.java:276)
    at com.outjected.email.impl.MailTransporterImpl.send(MailTransporterImpl.java:35)
    at com.outjected.email.impl.MailMessageImpl.send(MailMessageImpl.java:395)
    ... 74 more

Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
  nested exception is:
    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1961)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
    at javax.mail.Service.connect(Service.java:317)
    at javax.mail.Service.connect(Service.java:176)
    at javax.mail.Service.connect(Service.java:125)
    at javax.mail.Transport.send0(Transport.java:194)
    at javax.mail.Transport.send(Transport.java:124)
    at com.outjected.email.impl.util.MailUtility.send(MailUtility.java:273)
    ... 76 more

Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
    at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:296)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1509)
    at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216)
    at sun.security.ssl.Handshaker.processLoop(Handshaker.java:979)
    at sun.security.ssl.Handshaker.process_record(Handshaker.java:914)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387)
    at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:549)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:354)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:237)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1927)
    ... 83 more

Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
    at sun.security.validator.Validator.validate(Validator.java:260)
    at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1491)
    ... 94 more

Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:146)
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:131)
    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
    ... 100 more
  • I removed the greetings, not required in the template of the site, as can be read here: https://pt.meta.stackoverflow.com/q/846/28595

2 answers

1

I went through this problem, followed the next steps and it worked.

1- Follow the website steps: https://support.google.com/a/answer/176600?hl=en-PT or check if the properties are equal to the source at the end of the comment.

2- Add this properties. It was paramount for code operation: properties.put("mail.smtp.ssl.trust", "smtp.gmail.com")

3- Enable Google Authenticator. Grab the generated key to put into the code. The source below indicates where to put the generated key. How to create key tutorial: https://support.google.com/accounts/answer/1066447?co=GENIE.Platform%3DAndroid&hl=en

Finally, the code I implemented:

public static void enviaEmail(String destinatario, String assunto, String mensagem) throws Exception{       

        String porta = "465";

        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com" );
        props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
        props.put("mail.from", destinatario );
        props.put("mail.smtp.socketFactory.port", porta);
        props.put("mail.smtp.ssl.enable", true);
        props.put("mail.smtp.socketFactory.class",  "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", porta);
        props.put("mail.smtp.starttls.enable", "true");

        Session sessionEmail = Session.getInstance(props, null);


        try {
            MimeMessage msg = new MimeMessage(sessionEmail);
            msg.setFrom(destinatario);
            msg.setRecipients(Message.RecipientType.CC, "[email protected]" );
            msg.setSubject(assunto);
            msg.setReplyTo(InternetAddress.parse("[email protected]", false));
            msg.setSentDate(new Date());
            msg.setContent(mensagem, "text/html");
            Transport.send(msg, "[email protected]","***COLOQUEAQUI_A_CHAVE_DO_PASSO_3***");

        } catch (MessagingException mex) {
            log.error("Erro durante envio de email." + mex);
            throw mex;          
        }
    }

0

I have not tested your code, but port to Google smtp using SSL is the 587, this may be the problem with your code.

A complete example of how to send email using javax.mail can be seen here.

Update:

I forgot to inform you that when changing the port to 587 you must set the SSL setting to false and the TSL setting to true. You can check out a detailed code in the link above and in this response by SO EN.

And I also noticed that the property names are missing stmp, the correct names should be like this:

mail.smtp.starttls.enable -> true
mail.smtp.host -> smtp.gmail.com
mail.smtp.user -> nome de usuário da conta do gmail
mail.smtp.password  -> senha
mail.smtp.port -> 587
mail.smtp.auth -> true
  • I updated the answer. I hope it helps to solve your problem.

  • 1

    I managed to fix it. When you use Windows you need to disable the firewall and disable the anti-virus. Thanks for the force

Browser other questions tagged

You are not signed in. Login or sign up in order to post.