Error using Javamail with Office365 account

Asked

Viewed 1,815 times

1

I have a Java class that works perfectly to send emails through a Gmail account. However, even using the recommended settings to send an email via SMTP with Office365, an error is returned.

The error is as follows:

Exception javax.servlet.Servletexception: javax.mail.Messagingexception: Could not connect to SMTP host: smtp.office365.com, port: 587; nested Exception is: javax.net.ssl.Sslexception: Unrecognized SSL message, plaintext Connection?

Below is the code of my class:

public class GmailBean {

    public static final String SERVIDOR_SMTP = "smtp.office365.com";
    public static final int PORTA_SERVIDOR_SMTP = 587;
    private static final String CONTA_PADRAO = "[email protected]";
    private static final String SENHA_CONTA_PADRAO = "xxx";

    private String de;
    private String para;

    private String assunto;
    private String mensagem;

    public void enviarEmail() throws MessagingException {
        FacesContext context = FacesContext.getCurrentInstance();
        AutenticaUsuario autenticaUsuario = new AutenticaUsuario(GmailBean.CONTA_PADRAO, GmailBean.SENHA_CONTA_PADRAO);

        Session session = Session.getInstance(this.configuracaoEmail(), autenticaUsuario);

        // try{
        Transport envio = null;
        MimeMessage email = new MimeMessage(session);
        email.setRecipient(Message.RecipientType.TO, new InternetAddress(this.para));
        email.setFrom(new InternetAddress(this.de));
        email.setSubject(this.assunto);
        email.setContent(this.mensagem, "text/plain");
        email.setSentDate(new Date());
        envio = session.getTransport("smtp");
        envio.connect(GmailBean.SERVIDOR_SMTP, GmailBean.CONTA_PADRAO, GmailBean.SENHA_CONTA_PADRAO);
        email.saveChanges();
        envio.sendMessage(email, email.getAllRecipients());
        envio.close();

        context.addMessage(null, new FacesMessage("Mensagem enviada com sucesso!"));

        /* }
        catch(AddressException ex)
        { Logger logger = Logger.getAnonymousLogger();

        FacesMessage msg = new FacesMessage("Erro ao enviar mensagem "+ ex.getMessage());
        logger.info("Erro ao enviar mensagem _____________"+ ex.getMessage());
        }
        catch(MessagingException ex)
        {
        Logger logger = Logger.getAnonymousLogger();
        FacesMessage msg = new FacesMessage("Erro ao enviar mensagem "+ ex.getMessage());
        logger.info("Erro ao enviar mensagem _____________"+ ex.getMessage());

        }*/
    }

    public Properties configuracaoEmail() {
        Properties config = new Properties();

        config.put("mail.smtp.auth", "true");
        config.put("mail.transport.protocol", "smtp");
        config.put("mail.smtp.starttls.enabled", "true");
        config.put("mail.smtp.host", SERVIDOR_SMTP);
        config.put("mail.user", GmailBean.CONTA_PADRAO);
        config.put("mail.smtp.port", PORTA_SERVIDOR_SMTP);
        config.put("mail.smtp.socketFactory.port", PORTA_SERVIDOR_SMTP);
        config.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        config.put("mail.smtp.socketFactory.fallback", "false");

        return config;
    }

    // getters and setters

    class AutenticaUsuario extends Authenticator {

        private String usuario;
        private String senha;

        public AutenticaUsuario(String usuario, String senha) {

            this.usuario = usuario;
            this.senha = senha;

        }

        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(this.usuario, this.senha);
        }

    }

}
  • Have you tried without the information socketFactory and also using mail.smtp.starttls.enable in place of mail.smtp.starttls.enabled?

  • Bruno César, I modified the suggested property and commented on the lines that referred to socketFactory. Even so there is still error when sending the email. There would be some other setting to do that is specific to Office365?

  • Is the error the same? If not, what is it? It is another thing to check if the SMTP server is not SMTPS, then you change from .smtp. for .smtps. on the estates.

  • The error is as follows: javax.servlet.Servletexception: javax.mail.Messagingexception: Could not Convert socket to TLS;

  • Soon put a gist here and you test to see if it works, because I don’t have any accounts in office 365 to test. I tested yesterday in an example and the error was authentication, maybe it works for you.

  • 1

    See if this gist helps you. If not, report the error when using it.

  • Thank you, Bruno César! It worked perfectly. If you want, create an answer so that I can vote for it as correct.

  • Okay, I already include an answer for you.

Show 3 more comments

1 answer

0


According to the message:

Could not connect to SMTP host: smtp.office365.com, port: 587; nested Exception is: javax.net.ssl.Sslexception: Unrecognized SSL message, plaintext Connection?

The problem is the use of SSL for traffic of a message in a channel that does not recognize it. By default the SMTP of Office 365 uses TLS explicit, that is, the TLS (the property mail.smtp.starttls.enable) and no information of SSL.

So, some changes to be made:

  • alter of mail.smtp.starttls.enable for mail.smtp.starttls.enable
  • not enable SSL, remove all properties containing mail.smtp.socketFactory, one of which is a SSL Socket Factory

In the end, the properties will stay of this type:

config.put("mail.smtp.auth", "true");
config.put("mail.smtp.starttls.enable", "true");
config.put("mail.smtp.host", "smtp.office365.com");
config.put("mail.smtp.port", 587);

From the rest, your code is OK. See a full example on this gist.

P.S.: to Office 365 community is not working, there are some references on the issue SSL/TLS. As soon as I return I will update this reply with more details.

Browser other questions tagged

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