Susie Susie - 8 months ago 53
Java Question

MailConnectException while sending mail using java mail api

Trying to send an email using java mail api. And I keep getting MailConnectException. I have tried multiple ways to solve it without success.

Exception is thrown by this statement

transport.connect("", "", "myPassword");

Can anyone tell me what I'm doing wrong?

public static void main(String[] args) {
String host = "";
String from = "";
Properties props = System.getProperties();
props.put("", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", "myPassword");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipients(Message.RecipientType.TO, "");
message.setSubject("sending in a group");
message.setText("Welcome to JavaMail");
Transport transport = session.getTransport("smtp");
transport.connect("", "", "myPassword");//CAUSES EXCEPTION
transport.sendMessage(message, message.getAllRecipients());
}catch(MessagingException e){

Stack trace:

com.sun.mail.util.MailConnectException: Couldn't connect to host, port:, 465; timeout -1;
nested exception is: Connection timed out: connect
at com.sun.mail.smtp.SMTPTransport.openServer(
at com.sun.mail.smtp.SMTPTransport.protocolConnect(
at javax.mail.Service.connect(
at javax.mail.Service.connect(
at com.karmacrafts.util.CustomEmail.main(
Caused by: Connection timed out: connect
at Method)
at Source)
at Source)
at Source)
at Source)
at Source)
at Source)
at com.sun.mail.util.SocketFetcher.createSocket(
at com.sun.mail.util.SocketFetcher.getSocket(
at com.sun.mail.smtp.SMTPTransport.openServer(
... 4 more


This looks like network problem. Even though it could occur due to variety of reasons, like :-

"Couldn't connect to host, port" could be caused by wrong host name, wrong port, a blocking firewall (on the server, on gateways, even on your own machine), network failure, server downtime, etc.

Can you connect to the mail server using telnet ?

Also see this FAQ for some mistakes you committed

Read this answer on how to send emails using gmail