Problema com envio de e-mail

Olá amigos…

Já vi aqui alguns tópicos sobre o assunto, mas nenhum que resolvesse meu problema! Sou novo aqui, mas sou colaborador a algum tempo no pt.StackOverFlow… lá também não consegui a resolução para meu problema :’(
Enfim… vamos aos códigos!!!

Estou batendo com o seguinte erro (que é um erro duplo):

[2016-06-21 14:51:47,773] [http-8080-2] [7C3E2C073179A2DD592B01F9E385BF1B] [nan.base.BaseBO.closeConnection] #### FECHANDO CONHEXAO jdbc:sqlserver://192.168.1.15:1433;xopenStates=false;sendTimeAsDatetime=true;trustServerCertificate=false;sendStringParametersAsUnicode=true;selectMethod=direct;responseBuffering=adaptive;packetSize=8000;loginTimeout=15;lockTimeout=-1;lastUpdateCount=true;encrypt=false;disableStatementPooling=true;databaseName=negocio_prod_03032016;applicationName=Microsoft SQL Server JDBC Driver;, UserName=sa, Microsoft SQL Server JDBC Driver 3.0
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
nested exception is:
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
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 br.com.sebrae.nan.util.Mail.sendMail(Mail.java:79)
at br.com.sebrae.nan.action.usuario.RecuperarSenhaAction.execute(RecuperarSenhaAction.java:61)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:421)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:226)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1164)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:415)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:643)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.displaytag.filter.ResponseOverrideFilter.doFilter(ResponseOverrideFilter.java:125)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at br.com.sebrae.nan.base.DisableUrlSessionFilter.doFilter(DisableUrlSessionFilter.java:79)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at br.com.sebrae.nan.base.MDCLog4jFilter.doFilter(MDCLog4jFilter.java:37)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:612)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:503)
at java.lang.Thread.run(Thread.java:662)
Caused by: javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
at com.sun.net.ssl.internal.ssl.InputRecord.handleUnknownRecord(InputRecord.java:652)
at com.sun.net.ssl.internal.ssl.InputRecord.read(InputRecord.java:484)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:863)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1188)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1215)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1199)
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)
… 35 more

Segue minha classe de configuração:

package br.com.sebrae.nan.util;

import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.Context;
import javax.naming.InitialContext;

import br.com.sebrae.nan.dao.ConfiguracaoDAO;


public class Mail{

    public static boolean sendMail(String subject, String recipient, String ccRecipient, String bccRecipient, String body, boolean html, Long codSebrae) throws Exception{
        String smtpServer ="smtp.gmail.com"; //new ConfiguracaoDAO().getValorPorChave("SMTPServer", codSebrae);
        if(smtpServer != null && !smtpServer.equals("")){
            // Configura a sessao
            Properties mailProps = System.getProperties();
            
            Context initCtx = new InitialContext();
            Context envCtx = (Context) initCtx.lookup("java:comp/env");
            Session mailSession = (Session) envCtx.lookup("mail/Session");
            
            final String usuario = mailSession.getProperty("mail.smtp.user");
            final String senha = mailSession.getProperty("mail.smtp.password");

            //autenticação
            mailProps.put("mail.smtp.host", mailSession.getProperty("mail.smtp.host"));
        //    mailProps.put("mail.smtp.starttls.enable",  mailSession.getProperty("mail.smtp.starttls.enable"));
            mailProps.put("mail.smtp.auth",  mailSession.getProperty("mail.smtp.auth"));
            mailProps.put("mail.smtp.port",  mailSession.getProperty("mail.smtp.port"));
            mailProps.put("mail.smtp.ssl.enable", "true");
            mailProps.put("mail.smtp.starttls.enable", "true");
//            mailProps.put("mail.smtp.socketFactory.fallback","true");// Should be true
            
            
             Authenticator authenticator = new Authenticator() {  
                    protected PasswordAuthentication getPasswordAuthentication() {  
                    if ((usuario != null) && (usuario.length() > 0) && (senha != null) 
                                  && (senha.length   () > 0)) {
                        return new PasswordAuthentication(usuario,senha);  
                    }
                    return null;
                    }  
                };
            
            mailSession = Session.getDefaultInstance(mailProps, authenticator);
            mailSession.setDebug(false);
            // Configura��o da mensagem
            Message message = new MimeMessage(mailSession);
            message.setFrom(new InternetAddress(usuario));
            // Configura��o do Destinatario
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
            // Configura��o da lista de Carbon Copy
            if(ccRecipient != null){
                message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccRecipient, false));
            }
            // Configura��o da lista de Blind Carbon Copy
            if(bccRecipient != null){
                message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bccRecipient, false));
            }
            // Configura�ao do cabecalho do email
            message.setSentDate(new Date());
            message.setSubject(subject);
            // Verifica se � um email com corpo escrito em HTML
            if(html){
                message.setContent(message.toString(), "text/html");
                message.setDataHandler(new DataHandler(body, "text/html"));
            }else{
                message.setContent(message.toString(), "text/plain");
                message.setText(body);
            }
            // Envia a mensagem
        
            Transport.send(message);
            return true;
        }
        return false;
    }
}

As configurações do meu Context.xml:

<code>
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
--><!-- The contents of this file will be loaded for each web application --><Context>

    <!-- Default set of monitored resources -->
    < WatchedResource>WEB-INF/web.xml</WatchedResource > 
    
    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->

    <!-- Uncomment this to enable Comet connection tacking (provides events
         on session expiration as well as webapp lifecycle) -->
    <!--
    <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
    -->
    
    < Resource auth="Container" mail.smtp.auth="true"
        mail.smtp.host="smtp.gmail.com" mail.smtp.port="587"
        mail.smtp.socketFactory.class="javax.net.ssl.SSLSocketFactory"
        mail.smtp.starttls.enable="true" mail.smtp.user="fabrica@infosolo.com.br"
        mail.transport.protocol="smtp" name="mail/Session" mail.smtp.password="CSPInfo317"
        type="javax.mail.Session" / >
    
    
<!--     <Resource auth="Container" driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver" -->
<!--   removeAbandonedTimeout="15" removeAbandoned="true" logAbandoned="true" -->
<!--   maxActive="10" maxIdle="5" maxWait="100" name="jdbc/NaN" password="Hnkx317314!" -->
<!--   type="javax.sql.DataSource" -->
<!--   url="jdbc:sqlserver://192.168.1.15:1433;databaseName=negocio_prod_03032016" -->
<!--   username="sa" /> -->
  
  < Resource auth="Container" driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
        maxActive="10" maxIdle="15" maxWait="-1" name="jdbc/NaN"
        password="Hnkx317314!" type="javax.sql.DataSource"
        url="jdbc:sqlserver://192.168.1.15:1433;databaseName=negocio_prod_03032016"
        username="sa" / >

<!--    <Resource auth="Container"  -->
<!--    mail.smtp.auth="true"  -->
<!--    mail.smtp.host="mail.infosolo.com.br"  -->
<!--    mail.smtp.port="587"  -->
<!--    mail.smtp.user="fabrica@infosolo.com.br"  -->
<!--    mail.transport.protocol="smtp"  -->
<!--    name="mail/Session"  -->
<!--    mail.smtp.password="CSPInfo317"  -->
<!--    type="javax.mail.Session"/> -->
   
<!--    <Resource type="javax.mail.Session"  -->
<!--    name="mail/Session"  -->
<!--    mail.transport.protocol="smtp"  -->
<!--    mail.smtp.user="fabrica@infosolo.com.br"  -->
<!--    mail.smtp.starttls.enable="true"  -->
<!--    mail.smtp.password="CSPInfo317"  -->
<!--    mail.smtp.socketFactory.class="javax.net.ssl.SSLSocketFactory"  -->
<!--    mail.smtp.port="587"  -->
<!--    mail.smtp.host="smtp.gmail.com"  -->
<!--    mail.smtp.auth="true"  -->
<!--    auth="Container"/> -->
   
 </ Contex t>
</code>

Minha Action da "Recuperação de senha":

<code>
package br.com.sebrae.nan.action.usuario;

import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.BaseAction;

import com.google.gson.JsonObject;



import atg.taglib.json.util.JSONException;
import atg.taglib.json.util.JSONObject;
import br.com.sebrae.nan.base.NaNSebraeLogger;
import br.com.sebrae.nan.bo.UsuarioBO;
import br.com.sebrae.nan.util.Constantes;
import br.com.sebrae.nan.util.Mail;
import br.com.sebrae.nan.vo.Usuario;

public class RecuperarSenhaAction extends Action {

    public boolean status;
    public String msg;
    
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws JSONException {
        
        String login= request.getParameter("login");
        String email= request.getParameter("email");
        
        Usuario usuario=null;
        response.setContentType("application/json; charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        JsonObject jsonObject = new JsonObject();

        try {
            usuario= new UsuarioBO().getUsuarioPorLogin(login);
            
            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        if(usuario!=null && usuario.getEmail().toUpperCase().equals(email.toUpperCase())){
            String novaSenha=this.geraStringAleatoria();
            try {
                new UsuarioBO().alterarSenhaRec(novaSenha, usuario.getCodigo());
                new Mail();
                Mail.sendMail("Recupeação de senha", usuario.getEmail(), "", "", "Caro usuário, uma nova senha foi solicitada para o seu perfil. A senha gerada foi ' "+
                         novaSenha+" ' . Sugerimos que altere esta senha no proximo acesso.<br/> Atenciosamente,<br/> Equipe Negocio a Negocio.", true, 1L );
                this.status = true;
                this.msg    = "Um email foi enviado para esta conta de usuário!";
                
            } catch (Exception e) {
                this.status = false;
                this.msg    = e.getMessage();
                e.printStackTrace();
            }
        }else{
                this.status = false;
                this.msg = "Usuário inexistente ou e-mail inválido.";
        }
        jsonObject.addProperty("status", this.status);
        jsonObject.addProperty("msg", this.msg);
        //jsonObject.put("status", this.status);
        //jsonObject.put("msg", this.msg);
        try{
            response.getWriter().write(jsonObject.toString());
        }catch(Exception ee){
            NaNSebraeLogger.error(ee, request);
        }
        
        return null;    
    }
    
    private String geraStringAleatoria(){
        String letras="AaBbCcDdEeFfGgHhIi!@#$%&*1234567890";
        String retorno="";
        for(int i=0;i<8;i++){
            int j= new Random().nextInt(34);
            retorno=retorno+letras.substring(j,j+1);
        }
        return retorno;    
    }
    

}

Sei que existem outros tópicos a respeito, mas nenhum de fato trouxe a resposta… ficaria muito grato se pudesse ajudar! Prometo colaborar sempre que possível.

1 curtida

Saiu bem estranha a configuração da formatação :neutral_face:
E eu pensei ter usado corretamente as tags de code

1 curtida

Galera… consegui resolver!! Para posteriores pessoas que entrarem por aqui e verem esse problema e não conseguiram resolver: No contexto do meu código e como ele foi desenvolvido, apenas alterei a porta de 587 para 465. Resolveu na mesma hora…

Espero, com isso, ajudar com a minha primeira contribuição por aqui!

2 curtidas