Padma
Padma

Reputation: 656

Email Client in java

try {
    Properties props = new Properties();
    props.put("mail.smtp.starttls.enable", "true"); 
    props.setProperty("mail.transport.protocol", "smtp");
    props.setProperty("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");
    props.put("mail.smtp.socketFactory.port", "587");
    props.put("mail.smtp.socketFactory.fallback", "false");
    props.setProperty("mail.user", "username");
    props.setProperty("mail.password", "password");
   
    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("username","password");
        }
    }); 
    session.setDebug(true);

    MimeMessage msg = new MimeMessage(session);

    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);

    msg.addRecipient(Message.RecipientType.TO,new InternetAddress(" Recipient mail id "));
   
    msg.setSubject(subject);
    Transport transport = session.getTransport();
    transport.connect();
    transport.sendMessage(msg,msg.getRecipients(Message.RecipientType.TO));
    transport.close();
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

I am using the above code to send an email to a Gmail account. I have set the SMTP host value smtp.gmail.com and port 465 in the properties. But the email is not sent and my app got stuck for a long time. After that, I am getting an error like given below

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

Can anyone tell what is the reason and how to resolve this issue?

Upvotes: 2

Views: 2143

Answers (1)

stacker
stacker

Reputation: 68942

Setting

props.put("mail.smtp.starttls.enable", "true");

enables tls which is on port 587 not 465

props.put("mail.smtp.port", "587");

See Google Doc

And check whether you really need these lines

props.put("mail.smtp.socketFactory.port", "587");
props.put("mail.smtp.socketFactory.fallback", "false");

Upvotes: 1

Related Questions