2

I am trying to send an email using gmail in a java application. However I keep getting this error.

Severe: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1

I hope someone can help me check if my code is wrong. I have been staring at it for awhile now and am quite stuck. Thanks!

My mailing code

public void sendEmail(String email){
    String to=email;
    String from="user@gmail.com";
    String host="smtp.gmail.com";

    Properties properties = System.getProperties();
    properties.put("mail.smtp.host", host);
    properties.put("mail.smtp.socketFactory.port", String.valueOf(465));
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.port", "465");
    properties.put("mail.smtp.starttls.enabled", String.valueOf(true));
    properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    //Session session = Session.getDefaultInstance(properties);

    Session session= Session.getInstance(properties, new javax.mail.Authenticator() {
        protected PasswordAuthentication getpPasswordAuthentication(){
        return new  PasswordAuthentication("user@gmail.com", "password");
        }
    });

    try{
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));

        //set subject header field
        message.setSubject("Password reset");
        //set actual message
        message.setText("Your password has been reset");
        //send message
        Transport.send(message);
        System.out.println("Email has been sent");
    }catch(MessagingException mex){
        mex.printStackTrace();
    }

}
JianYA
  • 2,750
  • 8
  • 60
  • 136
  • Are you sure the port is 465? – KevinO May 12 '16 at 15:50
  • Im not sure what other ports are there to try? – JianYA May 12 '16 at 15:55
  • [This post](http://stackoverflow.com/questions/15597616/sending-email-via-gmail-smtp-server-in-java), and [this post](http://stackoverflow.com/questions/18781556/send-a-mail-with-java-and-gmail), and [this post](http://stackoverflow.com/questions/15597616/sending-email-via-gmail-smtp-server-in-java) all seem to imply port 587. – KevinO May 12 '16 at 15:58
  • Oh thanks. I've changed it now but its saying this. Severe: javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted. I dont have 2 step authentication on so im not sure whats going on – JianYA May 12 '16 at 16:15
  • See the [JavaMail FAQ entry on using Gmail](http://www.oracle.com/technetwork/java/javamail/faq/index.html#gmail). – Bill Shannon May 12 '16 at 21:54
  • The JavaMail entry I used doesn't work for me. Is my code correct ? – JianYA May 12 '16 at 22:16

0 Answers0