JavaMail - Unable to send mail using SSL

1.1k views Asked by At

I'm trying to send the mail by enabling SSL using JavaMail with office365 as host. When I'm using the host as smtp.gmail.com then it's working fine but not working for smtp.office365.com Below is my approach:

public class SendMail
{

     public static void main(String args[]){
        String username = "[email protected]";
        String password = "abc123";
        Properties properties = new Properties();
        properties.put("mail.smtp.host", "smtp.office365.com");
        properties.put("mail.smtp.socketFactory.port",995);
        properties.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.ssl.enable", "true");

        Session session = null;

        if (authenticationRequired) {
          session = Session.getInstance(properties,
              new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(userName,password);
                }
              });
        }else{
             session = Session.getDefaultInstance(properties);  
       }
       try{
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(username));
            message.setSubject("Test mail");
            message.setContent("Test Mail", "text/html");
            message.setRecipients(Message.RecipientType.TO,InternetAddress.parse([email protected]));

            Transport transport = session.getTransport("smtp");
            transport.connect();
            transport.sendMessage(message,message.getAllRecipients());
       }catch(Exception e){
          e.printStack();
       }
     }
  }

It is throwing exception as - Could not connect to SMTP host: smtp.office365.com, port: 995 response: -1. I have also tried the port as 993 but that too also not working. Kindly help me out. Other approaches are also welcome

1

There are 1 answers

4
Raphael Milani On

As you said, works with gmail did you import the gmail´s certificate to your keystore?