javax.net.ssl.SSLException when sending mail using JavaMail

0

Good morning. I'm having trouble sending an email using JavaMail.

Returns the following exception:

  

(javax.mail.SendFailedException) javax.mail.SendFailedException: Sending failed; nested exception is: class javax.mail.MessagingException: Exception reading response; nested exception is: javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?

I have already analyzed other questions, such as:

link

However, the error still persists.

Note: I've already enabled the option to allow less secure applications from my account in Gmail. In addition, using the Glassfish application manages to send the email. Apparently the problem is with Apache Tomcat.

Follow the code:

Properties props = new Properties();

props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.socketFactory.port", "587");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "587");

Session session1 = Session.getInstance(props,
    new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("email", "senha");
        }
    });

/**
 * Ativa Debug para sessão
 */
session1.setDebug(true);

try {

    Message message = new MimeMessage(session1);
    message.setFrom(new InternetAddress("enviaremail")); //Remetente

    String destinatario = (String) session.getAttribute("email");

    Address[] toUser = InternetAddress //Destinatário(s)
        .parse(destinatario);

    message.setRecipients(Message.RecipientType.TO, toUser);
    message.setSubject("Novo E-mail!"); //Assunto
    message.setText("Olá. Você recebeu um novo e-mail.");
    /**
     * Método para enviar a mensagem
     * criada
     */
    Transport.send(message);

    System.out.println("Feito!!!");

} catch (MessagingException e) {
    throw new RuntimeException(e);
}
    
asked by anonymous 06.09.2018 / 14:14

1 answer

0

I have this example that worked with me with GMAIL was having the same SSL problem. Remembering that I had to configure a password in GMAIL that it generates there too, if it does not work, I just do not remember where it is.

private void sendEmail (Usuario usuario) throws Exception {

    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.from", "[email protected]");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.ssl.enable", "false");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "587");

    Authenticator authenticator = new Authenticator();
    props.setProperty("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName());

    Session session = Session.getInstance(props, authenticator);
    MimeMessage msg = new MimeMessage(session);
    msg.setFrom();
    msg.setRecipients(Message.RecipientType.TO, "[email protected]");  
    // also tried @gmail.com
    msg.setSubject("Recuperação De Senha - ESC Pizzaria");
    //msg.setSentDate(new Date());
    msg.setText("Usuário: " + usuario.getLoginUsuario() + "\n" + 
                "Este e-mail foi enviado por: http://www.escpizzaria.com.br" + "\n" + 
                "Você recebeu esta e-mail, pois você esqueceu sua senha na ESC Pizzaria." + "\n\n" + 
                "------------------------------------------------" + "\n" + 
                "IMPORTANTE!" + "\n" + 
                "------------------------------------------------" + "\n" + 
                "Se você não solicitou este lembrete de senha, por favor IGNORE e EXCLUA este e-mail imediatamente." + "\n\n" +
                "Dados Da Sua Conta:" + "\n" + 
                "Nome Do Usuário: " + usuario.getLoginUsuario() + "\n\n" +
                "Acesse O Link Abaixo Para Trocar A Senha: \n\n" +
                "http://localhost:4200/usuario/trocarSenha/" + usuario.getLoginUsuario() + "/token/" + usuario.getTokenAlterarSenhaUsuario() + "\n "
                );

    Transport transport;
    transport = session.getTransport("smtp");
    transport.connect();
    msg.saveChanges(); 
    transport.sendMessage(msg, msg.getAllRecipients());
    transport.close();
}

private class Authenticator extends javax.mail.Authenticator {

    private PasswordAuthentication passwordAuthentication;
    public Authenticator() {

        String username = "[email protected]";
        String password = "mnmzczvfwzsubrev";
        passwordAuthentication = new PasswordAuthentication(username, password);
    }

    protected PasswordAuthentication getPasswordAuthentication() {
        return passwordAuthentication;
    }
}
    
06.09.2018 / 22:23