After going through post provided for the same problem, I have written the following code. But I am getting the following exception :
javax.mail.MessagingException:
Could not connect to SMTP host: smtp.gmail.com, port: 587;
nested exception is: java.net.ConnectException: Connection timed out: connect
public static void main(String[] args) {
String to = "[email protected]" // valid gmail address.
String from = "[email protected]"; // valid gmail address
String host = "smtp.gmail.com";
String password = "****"; // password of the gmaill acc used in from
int port = 587;
Properties properties = System.getProperties();
properties.put("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.smtp.host",host );
properties.setProperty("mail.smtp.user", from);
properties.setProperty("mail.smtp.password", password);
properties.setProperty("mail.smtp.port", "587");
properties.setProperty("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(properties,null);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Test Mail");
message.setText("This is just a test mail generated");
Transport transport = session.getTransport("smtp");
transport.connect(host,from,password);
InternetAddress[] addresses = new InternetAddress[1];
addresses[0] = new InternetAddress(to);
transport.sendMessage(message,addresses);
System.out.println("Message Sent Successfully");
}catch(MessagingException excp){
System.out.println(excp);
}
}
Can somebody tell mistake that I am doing. Is there any setting in my gmail account which needs to be set to use the gmail smtp server?
There is a connection problem. first check the connectivity to "smtp.gmail.com" .
Goto Command Prompt and run ping command as follows.
ping smtp.gmail.com
if you don't get the reply from server there may be firewall issue.