Sending Email with Java

Asked

Viewed 603 times

1

This code that I am using to send email by Java last time I used in 2017 worked, however, I am trying to use it now and it does not work in any way, it does not send me the email in any way.

package model;

import org.apache.commons.mail.EmailException;

import org.apache.commons.mail.SimpleEmail;



public class Email {

private String nomeDestinatario;
private String emailDestinatario;
private String assunto;
private String mensagem;

public void setNomeDestinatario(String nomeDestinatario) {
    this.nomeDestinatario = nomeDestinatario;
}

public void setEmailDestinatario(String emailDestinatario) {
    this.emailDestinatario = emailDestinatario;
}

public void setAssunto(String assunto) {
    this.assunto = assunto;
}

public void setMensagem(String mensagem) {
    this.mensagem = mensagem;
}

public boolean enviar() {
    SimpleEmail email = new SimpleEmail();

    email.setHostName("smtp.gmail.com");

            email.setSmtpPort(587);
            email.setStartTLSEnabled(true);

           // email.setSslSmtpPort("456");
            //email.setSSLOnConnect(true);

    try {
        email.addTo( emailDestinatario , nomeDestinatario );
        email.setFrom( EmailAutenticacao.email , EmailAutenticacao.nome);
        email.setSubject( assunto );
        email.setMsg( mensagem );

        System.out.println("autenticando...");
        email.setAuthentication( EmailAutenticacao.email, EmailAutenticacao.senha );
        System.out.println("enviando...");
        System.out.println(email.send());
        System.out.println("Email enviado!");

        return true;
    } catch (EmailException e) {
        e.printStackTrace();
        return false;
    }
}
}


package model;

public class EmailAutenticacao {

public static final String nome = "name";
public static final String email = "[email protected]";
public static final String senha = "password";

}


{

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try {
        String acao = request.getParameter("acao");
        if (acao.equals("Cadastrar")) {
            Matricula matricula = new Matricula();
            matricula.setAluno(request.getParameter("txtAluno"));
            matricula.setCurso(request.getParameter("txtCurso"));
            matricula.setStatus(request.getParameter("txtStatus"));

            MatriculaDAO matriculaDAO = new MatriculaDAO();
            matriculaDAO.cadastrarMatricula(matricula);

            Email email = new Email();
            email.setNomeDestinatario("matricula");
            email.setEmailDestinatario("[email protected]");
            email.setAssunto("Confirmação de Matricula");
            email.setMensagem("Sua Matricula foi Efetuada com Sucesso!");
            if (email.enviar()) {
                response.getWriter().println("Enviado com sucesso");
            } else {
                response.getWriter().println("Nao enviou");
            }

            request.setAttribute("msg", "cadastrado com sucesso");
            RequestDispatcher rd = request.getRequestDispatcher("/admin/cadastro_matricula.jsp");
            rd.forward(request, response);
}

Error log:

Grave:   org.apache.commons.mail.EmailException: Sending the email to the following server failed : smtp.gmail.com:587
at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1421)
at org.apache.commons.mail.Email.send(Email.java:1448)
at model.Email.enviar(Email.java:49)
at controller.ControleMatricula.processRequest(ControleMatricula.java:38)
at controller.ControleMatricula.doPost(ControleMatricula.java:89)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.mail.MessagingException: Could not convert socket to TLS; nested exception is:
java.net.SocketException: Connection reset
at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:2000)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:709)
at javax.mail.Service.connect(Service.java:386)
at javax.mail.Service.connect(Service.java:245)
at javax.mail.Service.connect(Service.java:194)
at javax.mail.Transport.send0(Transport.java:253)
at javax.mail.Transport.send(Transport.java:124)
at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1411)
... 34 more
Caused by: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:209)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at sun.security.ssl.InputRecord.readFully(InputRecord.java:465)
at sun.security.ssl.InputRecord.read(InputRecord.java:503)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:973)
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:597)
at com.sun.mail.util.SocketFetcher.startTLS(SocketFetcher.java:524)
at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1995)
... 41 more
  • With the exception of?

  • He gives the information "successfully registered" actually he makes the registration in the bank but does not send the email no error returns.

  • If you do not send an email, at least an exception should be made

  • See the Java version, I think this apache lib only works with java 8.

  • I’m Using Netbeans IDE 8.2 and jdk 8.2

  • @Andréfilipe I will check here to see what exception he gives then. It is that I am so long without programming that I am half lost.

  • @Andréfilipe Grave: org.apache.Commons.mail.Emailexception: Sending the email to the following server failed : smtp.gmail.com:587 at org.apache.Commons.mail.Email.sendMimeMessage(Email.java:1421) at org.apache.Commons.mail.Email.send(Email.java:1448) at model.email.enviar(Email.java:49) at controller.ControleMatricula.processRequest(Controlematricula.java:38) at controller.ControleMatricula.doPost(Controlematricula.java:89) Caused by: javax.mail.Messagingexception: Could not Convert socket to TLS; nested Exception is: java.net.Socketexception: Connection reset

Show 2 more comments

2 answers

1

I believe it may be a block of Gmail related to less secure accesses, a Google security policy that blocks the sending of Email in your application.

Try this on your Gmail account:

1 - Access your Google account.

2 - In the left navigation panel, click Security.

3 - At the bottom of the page, in the Access panel the least secure app, click Enable Access.

Reference

  • Opa vlw help, I had already done it already, as I said the code in 2017 worked the same code in 2019 with zero change does not work, until I went to check if it had returned to disabled this security issue but is not enabled to allow the access to less secure app.

0

Make sure it’s not your antivirus that’s not blocking the upload. I was having this same problem and it was my Avast: I did a test, disabled Avast and ran the same code, and it worked!

Follow the step-by-step so that the antivirus doesn’t interfere: Enable Avast again. In the Avast interface click Settings->Active Protection-> In the Email module, click Customize-> And uncheck the "Scan Sent Emails (SMTP)-> OK

  • Here I use AVG, but I will make a test can be. Vlw the help!

Browser other questions tagged

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